oTree Hub Studio Heroku Forum Public projects Featured Example code Account Example code This page contains examples of how various oTree functions should be used.For example, search this page for before_next_page or after_all_players_arrive. gbat_fallback_solo_task_part2 / SoloTask.html From otree - snippets {{block title}} Single - player task {{endblock}} {{block content}} < p > < i > Here you can put a single - player task.... < / i > < / p > {{endblock}} gbat_fallback_solo_task_part2 / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'gbat_fallback_solo_task_part2' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class SoloTask(Page): pass page_sequence = [SoloTask] multi_page_timeout / Page1.html From otree - snippets {{block title}} Page 1 {{endblock}} {{block content}} < p > Page content goes here... < / p > {{next_button}} {{endblock}} multi_page_timeout / Page2.html From otree - snippets {{block title}} Page 2 {{endblock}} {{block content}} < p > Page content goes here... < / p > {{next_button}} {{endblock}} multi_page_timeout / Page3.html From otree - snippets {{block title}} Page 3 {{endblock}} {{block content}} < p > Page content goes here... < / p > {{next_button}} {{endblock}} multi_page_timeout / __init__.py From otree - snippets from otree.api import * doc = """ Timeout spanning multiple pages """ class C(BaseConstants): NAME_IN_URL = 'multi_page_timeout' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 TIMER_TEXT = "Time to complete this section:" class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass def get_timeout_seconds1(player: Player): participant = player.participant import time return participant.expiry - time.time() def is_displayed1(player: Player): """only returns True if there is time left.""" return get_timeout_seconds1(player) > 0 class Intro(Page): @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant import time participant.expiry = time.time() + 60 class Page1(Page): is_displayed = is_displayed1 get_timeout_seconds = get_timeout_seconds1 timer_text = C.TIMER_TEXT class Page2(Page): is_displayed = is_displayed1 get_timeout_seconds = get_timeout_seconds1 timer_text = C.TIMER_TEXT class Page3(Page): is_displayed = is_displayed1 timer_text = C.TIMER_TEXT get_timeout_seconds = get_timeout_seconds1 page_sequence = [Intro, Page1, Page2, Page3] multi_page_timeout / Intro.html From otree - snippets {{block title}} Introduction {{endblock}} {{block content}} < p > Press next to start the timer... < / p > {{next_button}} {{endblock}} custom_export_groups / __init__.py From otree - snippets from otree.api import * import random doc = """ custom_export: 1 row for each group """ class C(BaseConstants): NAME_IN_URL = 'custom_export' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): """generate some fake data for the export""" for g in subsession.get_groups(): g.gfield1 = random.randint(0, 100) class Group(BaseGroup): gfield1 = models.IntegerField() class Player(BasePlayer): pass # PAGES class MyPage(Page): pass page_sequence = [MyPage] def get_groups(players): """gets all groups that these players belong to, without duplicates""" already_added = set() groups = [] for p in players: group = p.group if group.id not in already_added: already_added.add(group.id) groups.append(group) return groups def custom_export(players): """ Export 1 row for each group """ yield ['session.code', 'round_number', 'group.id_in_subsession', 'group.gfield1'] for g in get_groups(players): yield [g.session.code, g.round_number, g.id_in_subsession, g.gfield1] custom_export_groups / Results.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{next_button}} {{endblock}} custom_export_groups / MyPage.html From otree - snippets {{block content}} < p > Go to the data export page.The downloaded file will have 1 row per group. < / p > {{endblock}} live_volunteer / __init__.py From otree - snippets from otree.api import * doc = """ Live volunteer's dilemma (first player to click moves everyone forward). """ class C(BaseConstants): NAME_IN_URL = 'live_volunteer' PLAYERS_PER_GROUP = 3 NUM_ROUNDS = 1 REWARD = cu(1000) VOLUNTEER_COST = cu(500) class Subsession(BaseSubsession): pass class Group(BaseGroup): has_volunteer = models.BooleanField(initial=False) class Player(BasePlayer): is_volunteer = models.BooleanField() volunteer_id = models.IntegerField() # PAGES class MyPage(Page): @staticmethod def is_displayed(player: Player): group = player.group return not group.has_volunteer @staticmethod def live_method(player: Player, data): group = player.group # print('data is', data) if group.has_volunteer: return if data.get('volunteer'): group.has_volunteer = True # mark all other players as non-volunteers for p in player.get_others_in_group(): p.payoff = C.REWARD p.is_volunteer = False # mark myself as a volunteer player.is_volunteer = True player.payoff = C.REWARD - C.VOLUNTEER_COST # broadcast to the group that the game is finished. return {0: dict(finished=True)} @staticmethod def error_message(player: Player, values): """Prevent users from proceeding before someone has volunteered.""" group = player.group if not group.has_volunteer: return "Can't move forward" class Results(Page): pass page_sequence = [MyPage, Results] live_volunteer / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} {{ if player.is_volunteer}} < p > You volunteered. < / p > {{ else}} < p > Someone else volunteered. < / p > {{endif}} < p > Your payoff is therefore {{player.payoff}}. < / p > {{next_button}} {{endblock}} live_volunteer / MyPage.html From otree - snippets {{block content}} < p > This is a volunteer dilemma with {{C.PLAYERS_PER_GROUP}} players per group. If someone in the group volunteers, each player will get a reward of {{C.REWARD}}. But the volunteer will pay a penalty of {{C.VOLUNTEER_COST}}. < / p > < button type = "button" class ="btn btn-primary" onclick="sendVolunteer()" > I volunteer < / button > < br > < br > < p > Here you can chat with your group.< / p > {{chat}} < script > function sendVolunteer() { liveSend({'volunteer': true}); } function liveRecv(data) { if (data.finished) { document.getElementById('form').submit(); } } document.addEventListener('DOMContentLoaded', (event) = > { liveSend({}); }); < / script > {{endblock}} css / __init__.py From otree - snippets from otree.api import * doc = """ Using CSS to style timer and chat box. """ class C(BaseConstants): NAME_IN_URL = 'css' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): timeout_seconds = 30 * 60 page_sequence = [MyPage] css / MyPage.html From otree - snippets {{block title}} Demo of custom styles {{endblock}} {{block content}} < style > .otree - timer { position: sticky; top: 0 px; } .chat - widget { position: fixed; bottom: 0 px; right: 0 px; max - width: 50 em; z - index: 100; background - color: # eee; padding: 1 em; } < / style > < p > Sticky timer and chat box in bottom - right corner. < / p > < p > Sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text < / p > < p > Sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text < / p > < p > Sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text < / p > < p > Sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text < / p > < p > Sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text < / p > < p > Sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text sample text < / p > < div class ="chat-widget" > < b > Chat with your group < / b > {{chat}} < / div > {{endblock}} audio_alert / __init__.py From otree - snippets from otree.api import * doc = """ Audio alert (speak some text to get the participant's attention, after a wait page) """ class C(BaseConstants): NAME_IN_URL = 'audio_alert' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 3 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class MyPage(Page): pass class GBAT(WaitPage): pass class Results(Page): pass page_sequence = [MyPage, GBAT, Results] audio_alert / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < script > function sayReady() { let msg = new SpeechSynthesisUtterance(); // or: de - DE, zh - CN, ja - JP, es - MX, etc. msg.language = 'en-US'; // actually better to use js_vars than double - braces msg.text = "Ready player {{ player.id_in_group }}"; window.speechSynthesis.speak(msg); } if (document.hidden) { sayReady(); } < / script > < p > < i > You should hear a voice saying the game is ready, if the user is in another tab when this page loads. < / i > < / p > {{next_button}} {{endblock}} audio_alert / MyPage.html From otree - snippets {{block title}} Game {{endblock}} {{block content}} < p > < i > Your game goes here... < / i > < / p > {{formfields}} {{next_button}} {{endblock}} balance_treatments_for_dropouts / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'balance_treatments_for_dropouts' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 TREATMENTS = ['red', 'blue', 'green'] class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): session = subsession.session session.completions_by_treatment = {color: 0 for color in C.TREATMENTS} class Group(BaseGroup): pass class Player(BasePlayer): color = models.StringField() # PAGES class Intro(Page): @staticmethod def before_next_page(player: Player, timeout_happened): session = player.session player.color = min( C.TREATMENTS, key=lambda color: session.completions_by_treatment[color], ) class Task(Page): @staticmethod def before_next_page(player: Player, timeout_happened): session = player.session session.completions_by_treatment[player.color] += 1 page_sequence = [Intro, Task] gbat_new_partners / __init__.py From otree - snippets from otree.api import * doc = """ group by arrival time, but in each round assign to a new partner. """ class C(BaseConstants): NAME_IN_URL = 'gbat_new_partners' PLAYERS_PER_GROUP = None NUM_ROUNDS = 3 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): session = subsession.session session.past_groups = [] def group_by_arrival_time_method(subsession: Subsession, waiting_players): session = subsession.session import itertools # this generates all possible pairs of waiting players # and checks if the group would be valid. for possible_group in itertools.combinations(waiting_players, 2): # use a set, so that we can easily compare even if order is different # e.g. {1, 2} == {2, 1} pair_ids = set(p.id_in_subsession for p in possible_group) # if this pair of players has not already been played if pair_ids not in session.past_groups: # mark this group as used, so we don't repeat it in the next round. session.past_groups.append(pair_ids) # in this function, # 'return' means we are creating a new group with this selected pair return possible_group class Group(BaseGroup): pass class Player(BasePlayer): pass class ResultsWaitPage(WaitPage): group_by_arrival_time = True body_text = "Waiting to pair you with someone you haven't already played with" class MyPage(Page): @staticmethod def vars_for_template(player: Player): return dict(partner=player.get_others_in_group()[0]) page_sequence = [ResultsWaitPage, MyPage] gbat_new_partners / MyPage.html From otree - snippets {{block title}} Round {{subsession.round_number}} {{endblock}} {{block content}} < p > < i > This game uses group_by_arrival_time for multiple rounds. In each round, we ensure that you are matched with a different player. < / i > < / p > < p > Your partner is player {{partner.id_in_subsession}}. < / p > < p > Here are the pairs that have already played together: {{session.past_groups}} < / p > {{next_button}} {{endblock}} gbat_treatments / __init__.py From otree - snippets from otree.api import * doc = """ Conventionally, group-level treatments are assigned in creating_session: for g in subsession.get_groups(): g.treatment = random.choice([True, False]) However, this doesn't work when using group_by_arrival_time, because groups are not determined until players arrive at the wait page. (All players are in the same group initially.) Instead, you need to assign treatments in after_all_players_arrive. """ class C(BaseConstants): NAME_IN_URL = 'gbat_treatments' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): treatment = models.BooleanField() class Player(BasePlayer): pass class GBATWaitPage(WaitPage): group_by_arrival_time = True @staticmethod def after_all_players_arrive(group: Group): import random group.treatment = random.choice([True, False]) class MyPage(Page): pass page_sequence = [GBATWaitPage, MyPage] balance_treatments_for_dropouts / Task.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > You were assigned to the < b > {{player.color}} < / b > treatment, because this treatment group currently was completed by the fewest number of players. < / p > {{next_button}} {{endblock}} balance_treatments_for_dropouts / Intro.html From otree - snippets {{block title}} {{endblock}} {{block content}} Welcome {{next_button}} {{endblock}} random_num_rounds_multiplayer / __init__.py From otree - snippets from otree.api import * doc = """ Random number of rounds for multiplayer (random stopping rule) """ class C(BaseConstants): NAME_IN_URL = 'random_num_rounds_multiplayer' PLAYERS_PER_GROUP = None # choose NUM_ROUNDS high enough that the chance of # maxing out is negligible NUM_ROUNDS = 50 STOPPING_PROBABILITY = 0.2 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): for p in subsession.get_players(): p.participant.finished_rounds = False class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): pass class ResultsWaitPage(WaitPage): @staticmethod def after_all_players_arrive(group: Group): import random if random.random() < C.STOPPING_PROBABILITY: print('ending game') for p in group.get_players(): p.participant.finished_rounds = True # your usual after_all_players_arrive goes here... class Results(Page): @staticmethod def app_after_this_page(player: Player, upcoming_apps): participant = player.participant if participant.finished_rounds: return upcoming_apps[0] page_sequence = [MyPage, ResultsWaitPage, Results] random_num_rounds_multiplayer / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > < i > Your results page goes here... < / i > < / p > {{ if participant.finished_rounds}} < p > The game was randomly determined to stop at this round. < / p > {{ else}} < p > The game will continue to the next round. < / p > {{endif}} {{formfields}} {{next_button}} {{endblock}} random_num_rounds_multiplayer / MyPage.html From otree - snippets {{block title}} Game {{endblock}} {{block content}} < p > This game uses a random stopping rule.After each round, the game has a probability of {{C.STOPPING_PROBABILITY}} of being stopped. < / p > < p > < i > Your game goes here... < / i > < / p > {{formfields}} {{next_button}} {{endblock}} timer_custom / __init__.py From otree - snippets from otree.api import * doc = """ Timer: replacing the default timer with your own """ class C(BaseConstants): NAME_IN_URL = 'timer_custom' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): timeout_seconds = 60 page_sequence = [MyPage] timer_custom / MyPage.html From otree - snippets {{block title}} Custom timer element {{endblock}} {{block content}} < p > You have < span id = "time-left" > < / span > seconds left. < / p > {{formfields}} {{next_button}} < script > let customTimerEle = document.getElementById('time-left'); document.addEventListener("DOMContentLoaded", function(event) { $('.otree-timer__time-left').on('update.countdown', function(event) { customTimerEle.innerText = event.offset.totalSeconds; }); }); < / script > {{endblock}} questions_from_csv_simple / __init__.py From otree - snippets from otree.api import * doc = """ Read quiz questions from a CSV (simple version). See also the 'complex' version of this app. """ def read_csv(): import csv f = open(__name__ + '/stimuli.csv', encoding='utf-8-sig') rows = list(csv.DictReader(f)) return rows class C(BaseConstants): NAME_IN_URL = 'questions_from_csv_simple' PLAYERS_PER_GROUP = None QUESTIONS = read_csv() NUM_ROUNDS = len(QUESTIONS) class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): current_question = C.QUESTIONS[subsession.round_number - 1] for p in subsession.get_players(): p.question = current_question['question'] p.optionA = current_question['optionA'] p.optionB = current_question['optionB'] p.optionC = current_question['optionC'] p.solution = current_question['solution'] p.participant.quiz_num_correct = 0 class Group(BaseGroup): pass class Player(BasePlayer): question = models.StringField() optionA = models.StringField() optionB = models.StringField() optionC = models.StringField() solution = models.StringField() choice = models.StringField(widget=widgets.RadioSelect) is_correct = models.BooleanField() def choice_choices(player: Player): return [ ['A', player.optionA], ['B', player.optionB], ['C', player.optionC], ] class Stimuli(Page): form_model = 'player' form_fields = ['choice'] @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant player.is_correct = player.choice == player.solution participant.quiz_num_correct += int(player.is_correct) class Results(Page): @staticmethod def is_displayed(player: Player): return player.round_number == C.NUM_ROUNDS @staticmethod def vars_for_template(player: Player): return dict(round_players=player.in_all_rounds()) page_sequence = [Stimuli, Results] questions_from_csv_simple / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > You gave {{participant.quiz_num_correct}} correct answers. < / p > < table class ="table" > < tr > < th > question < / th > < th > optionA < / th > < th > optionB < / th > < th > optionC < / th > < th > Your choice < / th > < th > solution < / th > < th > correct? < / th > < / tr > {{ for p in round_players}} < tr > < td > {{p.question}} < / td > < td > {{p.optionA}} < / td > < td > {{p.optionB}} < / td > < td > {{p.optionC}} < / td > < td > {{p.choice}} < / td > < td > {{p.solution}} < / td > < td > {{p.is_correct}} < / td > < / tr > {{endfor}} < / table > {{endblock}} pay_random_app_single_player / __init__.py From otree - snippets from otree.api import * doc = """ """ class C(BaseConstants): NAME_IN_URL = 'pay_random_app2' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): for p in subsession.get_players(): # initialize an empty dict to store how much they made in each app p.participant.app_payoffs = {} class Group(BaseGroup): pass class Player(BasePlayer): potential_payoff = models.CurrencyField() # PAGES class MyPage(Page): @staticmethod def before_next_page(player: Player, timeout_happened): """in a single-player game you typically set payoff in before_next_page, so that's what we demonstrate here. """ participant = player.participant import random potential_payoff = random.randint(100, 200) player.potential_payoff = potential_payoff # this is designed for apps that have a single round. # if your app has multiple rounds, see the pay_random_round app. participant.app_payoffs[__name__] = potential_payoff class Results(Page): pass page_sequence = [MyPage, Results] pay_random_app_single_player / Results.html From otree - snippets {{block title}} App 2 Results {{endblock}} {{block content}} < p > Your payoff in this app is {{player.potential_payoff}}. < / p > {{next_button}} {{endblock}} pay_random_app_single_player / MyPage.html From otree - snippets {{block title}} App 2 {{endblock}} {{block content}} < p > < i > Your game would normally go here.In this case, your payoff will be determined randomly. < / i > < / p > {{next_button}} {{endblock}} back_button / Task.html From otree - snippets {{block title}} Task {{endblock}} {{block content}} < p > < i > Experiment goes here... < / i > < / p > {{next_button}} {{endblock}} back_button / Instructions.html From otree - snippets {{block title}} Instructions {{endblock}} {{block content}} < style > .tab { display: none; } < / style > {{include_sibling 'tabs.html'}} < script > let activeTab = 0; let tabs = document.getElementsByClassName('tab'); function showCurrentTabOnly() { for (let i = 0; i < tabs.length; i++) { let tab = tabs[i]; if (i == = activeTab) { tab.style.display = 'block'; tab.scrollIntoView(); } else { tab.style.display = 'none'; } } } showCurrentTabOnly(); for (let btn of document.getElementsByClassName('btn-tab')) { btn.onclick = function () { activeTab += parseInt(btn.dataset.offset); showCurrentTabOnly(); } } < / script > {{endblock}} questions_from_csv_simple / Stimuli.html From otree - snippets {{block title}} Question {{player.round_number}} of {{C.NUM_ROUNDS}} {{endblock}} {{block content}} < p > < b > {{player.question}} < / b > < / p > {{formfields}} {{next_button}} {{endblock}} gbat_fallback_solo_task_part0 / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'gbat_fallback_solo_task_part0' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class MyPage(Page): @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant import time participant.wait_page_arrival = time.time() page_sequence = [MyPage] gbat_fallback_solo_task_part0 / MyPage.html From otree - snippets {{block title}} Welcome {{endblock}} {{block content}} < p > Welcome! Please press next. You will be grouped with another participant. If we cannot group you with another participant within a minute, you will proceed to a single - player task. < / p > {{next_button}} {{endblock}} back_button / __init__.py From otree - snippets from otree.api import * doc = """ Back button for multiple instructions pages """ class C(BaseConstants): NAME_IN_URL = 'back_button' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class Instructions(Page): pass class Task(Page): pass page_sequence = [Instructions, Task] back_button / tabs.html From otree - snippets < div class ="tab" > Instructions first page content goes here... Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum < p > < button type = "button" class ="btn-tab" data-offset="1" > Next < / button > < / p > < / div > < div class ="tab" > < !-- Duplicate this div if you have more than 3 pages of instructions... --> Instructions middle page content goes here. Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum Lorem ipsum lorem ipsum < p > < button type = "button" class ="btn-tab" data-offset="-1" > Previous < / button > < button type = "button" class ="btn-tab" data-offset="1" > Next < / button > < / p > < / div > < div class ="tab" > Instructions last page content goes here... < p > < button type = "button" class ="btn-tab" data-offset="-1" > Previous < / button > < button class ="btn btn-primary" > Next < / button > < / p > < / div > other_player_previous_rounds / __init__.py From otree - snippets from otree.api import * doc = """ Showing other players' decisions from previous rounds """ class C(BaseConstants): NAME_IN_URL = 'other_player_previous_rounds' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 5 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): import random subsession.group_randomly() # for demo purposes we just generate random data. # of course in a real game, there would be a formfield where a user # enters their contribution for player in subsession.get_players(): player.contribution = random.randint(0, 99) class Group(BaseGroup): pass class Player(BasePlayer): contribution = models.IntegerField() def get_partner(player: Player): return player.get_others_in_group()[0] # PAGES class MyPage(Page): @staticmethod def vars_for_template(player: Player): partner = get_partner(player) my_partner_previous = partner.in_all_rounds() my_previous_partners = [ get_partner(me_prev) for me_prev in player.in_all_rounds() ] return dict( partner=partner, my_partner_previous=my_partner_previous, my_previous_partners=my_previous_partners, ) page_sequence = [MyPage] other_player_previous_rounds / MyPage.html From otree - snippets {{block title}} Round {{subsession.round_number}} {{endblock}} {{block content}} < p > < i > This app shows how you can chain methods like < code >.in_all_rounds() < / code > with < code > group.get_players() < / code >, < code > player.get_others_in_group() < / code >, etc, to get the history of other players in different ways. < / i > < / p > < h3 > My current partner 's history < p > My current partner: player {{partner.id_in_subsession}} < / p > < table class ="table" > < tr > < th > Round < / th > < th > contribution < / th > < / tr > {{ for p in my_partner_previous}} < tr > < td > {{p.round_number}} < / td > < td > {{p.contribution}} < / td > < / tr > {{endfor}} < / table > < h3 > History of my partners < / h3 > < table class ="table" > < tr > < th > Round < / th > < th > Player < / th > < th > contribution < / th > < / tr > {{ for p in my_previous_partners}} < tr > < td > {{p.round_number}} < / td > < td > {{p.id_in_subsession}} < / td > < td > {{p.contribution}} < / td > < / tr > {{endfor}} < / table > {{next_button}} {{endblock}} slider_live_label / __init__.py From otree - snippets from otree.api import * doc = """ Slider with live updating label """ class C(BaseConstants): NAME_IN_URL = 'slider_live_label' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 ENDOWMENT = 100 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): give = models.IntegerField( min=0, max=C.ENDOWMENT, label="How much do you want to give?" ) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['give'] @staticmethod def js_vars(player: Player): return dict(endowment=C.ENDOWMENT) page_sequence = [MyPage] dropout_detection / Page1.html From otree - snippets {{block content}} < p > You need to submit this page before the timeout occurs. Otherwise you will be considered a dropout. < / p > < p > < i > You can put formfields on this page etc. < / i > < / p > {{next_button}} {{endblock}} dropout_detection / Page2.html From otree - snippets {{block content}} < p > < i > Experiment continues here... < / i > < / p > {{next_button}} {{endblock}} chat_with_experimenter / MyPage.html From otree - snippets {{block title}} Chat with experimenter {{endblock}} {{block content}} < p > In the bottom right corner of the screen, there is a button to start a chat with the experimenter. < / p > < p > < i > In this demo, these messages are currently being sent to oTree.org 's Papercups server. To set up your own server, See < a href = "https://otree.readthedocs.io/en/latest/admin.html#experimenter-chat" > here < / a >. < / i > < / p > { # you should put this 'include' on every page that needs a chat widget #} {{include_sibling 'papercups.html'}} {{endblock}} chat_with_experimenter / __init__.py From otree - snippets from otree.api import * doc = """ Chat with experimenter, using Papercups """ class C(BaseConstants): NAME_IN_URL = 'chat_with_experimenter' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): pass page_sequence = [MyPage] experimenter_input / Intro.html From otree - snippets {{block content}} < p > < i > Put the first part of your game here... < / i > < / p > {{next_button}} {{endblock}} experimenter_input / MyPage.html From otree - snippets {{block content}} < p > The number drawn by the experimenter was {{group.exp_input}}. < / p > < p > < i > Your game can continue here.... < / i > < / p > {{endblock}} dropout_detection / __init__.py From otree - snippets from otree.api import * doc = """ Dropout detection (if user does not submit page in time) """ class C(BaseConstants): NAME_IN_URL = 'detect_dropout' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): is_dropout = models.BooleanField(initial=False) class Page1(Page): timeout_seconds = 10 @staticmethod def before_next_page(player: Player, timeout_happened): # note: bugfix if timeout_happened: player.is_dropout = True class ByeDropout(Page): @staticmethod def is_displayed(player: Player): return player.is_dropout @staticmethod def error_message(player: Player, values): return "Cannot proceed past this page" class Page2(Page): pass page_sequence = [Page1, ByeDropout, Page2] dropout_detection / ByeDropout.html From otree - snippets {{block title}} End {{endblock}} {{block content}} Sorry, you did not submit the page in time. The experiment is now finished. {{endblock}} experimenter_input / __init__.py From otree - snippets from otree.api import * doc = """ Experimenter input during the experiment, e.g. entering the result of a random draw. If you want the experimenter to be able to make an input at any time, you can use the REST API (especially the session_vars endpoint). """ class C(BaseConstants): NAME_IN_URL = 'experimenter_input' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 PASSWORD = 'mypass' class Subsession(BaseSubsession): pass class Group(BaseGroup): exp_input = models.IntegerField() has_exp_input = models.BooleanField(initial=False) class Player(BasePlayer): pass # PAGES class Intro(Page): pass class ExpInput(Page): """ It should be a live page so that you can notify all other players to advance """ @staticmethod def live_method(player: Player, data): group = player.group if ('exp_input' in data) and ('password' in data): if data['password'] != C.PASSWORD: return {player.id_in_group: dict(error="Incorrect password")} group.exp_input = data['exp_input'] group.has_exp_input = True # broadcast to the whole group whether the game is finished return {0: dict(finished=group.has_exp_input)} @staticmethod def error_message(player: Player, values): group = player.group if not group.has_exp_input: return "Experimenter has not input data yet" class MyPage(Page): pass page_sequence = [Intro, ExpInput, MyPage] experimenter_input / ExpInput.html From otree - snippets {{block title}} Random draw {{endblock}} {{block content}} < p > Please wait.The experimenter will draw a random number. < / p > < details > < summary > If you are the experimenter, click here. < / summary > < label class ="col-form-label" > Number drawn < input type = "number" class ="form-control" id="exp_input" > < / label > < br > < label class ="col-form-label" > Password { # you can add type="password" for a proper password input #} < input class ="form-control" id="password" > < / label > < br > < button type = "button" onclick = "sendData()" > Submit < / button > < p > < small > Hint for demo purposes: password is "{{ C.PASSWORD }}". You can get to this page by opening the participant 's start URL. < / small > < / p > < / details > < script > let expInput = document.getElementById('exp_input'); let passwordInput = document.getElementById('password'); function sendData() { liveSend({'exp_input': parseInt(expInput.value), password: passwordInput.value}); } function liveRecv(data) { if (data.finished) { document.getElementById('form').submit(); } if (data.error) { alert(data.error); } } document.addEventListener("DOMContentLoaded", function(event) { // need this so that you proceed even if you arrive late or got disconnected liveSend({}); }); < / script > {{endblock}} multi_language / __init__.py From otree - snippets import random from otree.api import * from settings import LANGUAGE_CODE doc = """ How to translate an app to multiple languages (e.g. English and German). There are 2 ways to define localizable strings: (1) Put it in a "lexicon" file (see lexicon_en.py, lexicon_de.py). This is the easiest technique, and it allows you to easily reuse the same string multiple times. (2) If the string contains variables, then it should to be defined in the template. Use an if-statement, like {{ if de }} Nein {{ else }} No {{ endif }} When you change the LANGUAGE_CODE in settings.py, the language will automatically be changed. Note: this technique does not require .po files, which are a more complex technique. """ if LANGUAGE_CODE == 'de': from .lexicon_de import Lexicon else: from .lexicon_en import Lexicon # this is the dict you should pass to each page in vars_for_template, # enabling you to do if-statements like {{ if de }} Nein {{ else }} No {{ endif }} which_language = {'en': False, 'de': False, 'zh': False} # noqa which_language[LANGUAGE_CODE[:2]] = True class C(BaseConstants): NAME_IN_URL = 'bret' NUM_ROUNDS = 1 PLAYERS_PER_GROUP = None class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): boxes_collected = models.IntegerField(label=Lexicon.boxes_collected) class Game(Page): form_model = 'player' form_fields = ['boxes_collected'] @staticmethod def vars_for_template(player: Player): return dict(Lexicon=Lexicon, **which_language) class Results(Page): @staticmethod def vars_for_template(player: Player): # this is just fake data return dict( boxes_total=64, bomb_row=2, bomb_col=1, bomb=True, payoff=player.payoff, box_value=cu(5), boxes_collected=player.boxes_collected, Lexicon=Lexicon, **which_language ) page_sequence = [Game, Results] multi_language / Results.html From otree - snippets {{block title}} {{Lexicon.results}} {{endblock}} {{block content}} {{ if de}} Sie haben sich entschieden {{boxes_collected}} von {{boxes_total}} Boxen zu sammeln. {{ else}} You chose to collect {{boxes_collected}} out of {{boxes_total}} boxes. {{endif}} < p > {{ if de}} Die Bombe war hinter der Box in Reihe {{bomb_row}}, Spalte {{bomb_col}} versteckt. {{ else}} The bomb was hidden behind the box in row {{bomb_row}}, column {{bomb_col}}. {{endif}} < / p > < p > {{ if bomb}} {{ if de}} Die Bombe befand sich unter den von Ihnen gesammelten {{boxes_collected}} Boxen. < br / > Entsprechend wurden alle Ihre gesammelten Erträge zerstört und Ihre Auszahlung in dieser Aufgabe beträgt {{player.payoff}}. {{ else}} The bomb was among your {{boxes_collected}} collected boxes. < br / > Accordingly, all your earnings in this task were destroyed and your payoff amounts to {{player.payoff}}. {{endif}} {{ else}} {{ if de}} Die Bombe war nicht unter den von Ihnen eingesammelten Boxen. < br / > Dementsprechend erhalten Sie {{box_value}} für jede der {{boxes_collected}} Boxen, sodass sich Ihre Auszahlung in dieser Aufgabe auf < b > {{player.payoff}} < / b > beläuft. {{ else}} Your collected boxes did not contain the bomb. < br / > Thus, you receive {{box_value}} for each of the {{boxes_collected}} boxes you collected such that your payoff from this task amounts to < b > {{player.payoff}} < / b >. {{endif}} {{endif}} < / p > {{next_button}} {{endblock}} multi_language / Game.html From otree - snippets {{block title}} {{Lexicon.your_decision}} {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} gbat_fallback_smaller_group_part1 / __init__.py From otree - snippets from otree.api import * doc = """ group_by_arrival_time: fall back to a smaller group if not enough people show up """ class C(BaseConstants): NAME_IN_URL = 'gbat_fallback_smaller_group_part1' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def waiting_seconds(player): import time participant = player.participant wait = int(time.time() - participant.wait_page_arrival) # print('Player', player.id_in_subsession, 'waiting for', wait, 'seconds') return wait def ranked_waiting_seconds(waiting_players): waits = [waiting_seconds(p) for p in waiting_players] waits.sort(reverse=True) return waits def group_by_arrival_time_method(subsession, waiting_players): # print("number of players waiting:", len(waiting_players)) # ideal case if len(waiting_players) >= 4: print("Creating a full sized group!") return waiting_players[:4] waits = ranked_waiting_seconds(waiting_players) if len(waits) == 3 and waits[2] > 60: print( "3 players have been waiting for longer than a minute, " "so we settle for a group of 3" ) return waiting_players if len(waits) >= 2 and waits[1] > 2 * 60: print( "2 players have been waiting for longer than 2 minutes, " "so we group whoever is available" ) return waiting_players # you can add your own additional rules based on waiting time and # number of waiting players class Group(BaseGroup): pass class Player(BasePlayer): favorite_color = models.StringField(label="What is your favorite color?") class GBAT(WaitPage): group_by_arrival_time = True class GroupTask(Page): form_model = 'player' form_fields = ['favorite_color'] class MyWait(WaitPage): pass class Results(Page): pass page_sequence = [GBAT, GroupTask, MyWait, Results] gbat_fallback_smaller_group_part1 / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > The colors chosen in your group were: < / p > < ul > {{ for p in group.get_players()}} < li > {{p.favorite_color}} < / li > {{endfor}} < / ul > {{next_button}} {{endblock}} gbat_fallback_smaller_group_part1 / GroupTask.html From otree - snippets {{block content}} < p > Your game goes here... < / p > {{formfields}} {{next_button}} {{endblock}} save_wrong_answers / Failed.html From otree - snippets {{block content}} Sorry, you gave too many wrong answers to the comprehension test. {{endblock}} save_wrong_answers / __init__.py From otree - snippets from otree.api import * doc = """ Store the history of invalid responses a user made. """ class C(BaseConstants): NAME_IN_URL = 'save_wrong_answers' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): quiz1 = models.IntegerField(label='What is 2 + 2?') quiz2 = models.StringField( label='What is the capital of Canada?', choices=['Ottawa', 'Toronto', 'Vancouver'], ) quiz3 = models.IntegerField(label="What year did COVID-19 start?") quiz4 = models.BooleanField(label="Is 4 a prime number") class IncorrectResponse(ExtraModel): player = models.Link(Player) field_name = models.StringField() response = models.StringField() class MyPage(Page): form_model = 'player' form_fields = ['quiz1', 'quiz2', 'quiz3', 'quiz4'] @staticmethod def error_message(player: Player, values): solutions = dict(quiz1=4, quiz2='Ottawa', quiz3=2019, quiz4=False) errors = {name: 'Try again' for name in solutions if values[name] != solutions[name]} if errors: for name in errors: response = values[name] IncorrectResponse.create(player=player, field_name=name, response=str(response)) return errors class Results(Page): pass page_sequence = [MyPage, Results] def custom_export(players): """For data export page""" yield ['participant_code', 'id_in_session', 'round_number', 'field_name', 'response'] responses = IncorrectResponse.filter() for resp in responses: player = resp.player participant = player.participant yield [participant.code, participant.id_in_session, player.round_number, resp.field_name, resp.response] save_wrong_answers / Results.html From otree - snippets {{block title}} Thank you {{endblock}} {{block content}} < p > You answered all questions correctly < / p > {{endblock}} save_wrong_answers / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} count_button_clicks / __init__.py From otree - snippets from otree.api import * doc = """Count button clicks""" class C(BaseConstants): NAME_IN_URL = 'count_button_clicks' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): button_clicks = models.IntegerField(initial=0) link_clicks = models.IntegerField(initial=0) # PAGES class MyPage(Page): @staticmethod def live_method(player: Player, data): if data == 'clicked-button': player.button_clicks += 1 if data == 'clicked-link': player.link_clicks += 1 class Results(Page): pass page_sequence = [MyPage, Results] count_button_clicks / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > You clicked the button {{player.button_clicks}} times and the link {{player.link_clicks}} times. < / p > {{endblock}} count_button_clicks / MyPage.html From otree - snippets {{block title}} Click the button {{endblock}} {{block content}} < p > This app records to the database the number of times you click the button or the link. < / p > < p > < button type = "button" onclick = "liveSend('clicked-button')" > Click me < / button > < a href = "https://wikipedia.org" onclick = "liveSend('clicked-link')" target = "_blank" > Click me < / a > < / p > {{next_button}} {{endblock}} slider_live_label / MyPage.html From otree - snippets {{block title}} {{endblock}} {{block content}} < p > Move the slider to decide how much to give. < / p > < input type = "range" name = "give" min = "0" max = "{{ C.ENDOWMENT }}" oninput = "updateDescription(this)" > < p id = "description" > < / p > < !-- by leaving the description blank initially, we prompt the user to move the slider, reducing the anchoring / default effect. --> < script > let description = document.getElementById('description'); function updateDescription(input) { let give = parseInt(input.value); let keep = js_vars.endowment - give; description.innerText = `Give ${give} points and keep ${keep} for yourself.` } < / script > {{next_button}} {{endblock}} constant_sum / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'constant_sum' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): a = models.CurrencyField() b = models.CurrencyField() c = models.CurrencyField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['a', 'b', 'c'] @staticmethod def error_message(player: Player, values): # since 'values' is a dict, you could also do sum(values.values()) if values['a'] + values['b'] + values['c'] != 100: return 'Numbers must add up to 100' page_sequence = [MyPage] constant_sum / MyPage.html From otree - snippets {{block content}} < p > Please split your 100 points between A, B, and C. < / p > {{formfields}} < p > < b > Total: < span id = "total" > < / span > < / b > < / p > < script > let inputlist = document.getElementsByTagName('input'); let totalDisplay = document.getElementById('total'); function updateSum() { let total = 0; for (let field of inputlist) { total += parseInt(input.value | | 0); } totalDisplay.innerText = total; } for (let input of inputlist) { input.oninput = updateSum; } < / script > {{next_button}} {{endblock}} history_table / __init__.py From otree - snippets from otree.api import * doc = """History table""" class C(BaseConstants): NAME_IN_URL = 'history_table' PLAYERS_PER_GROUP = None NUM_ROUNDS = 10 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): number = models.IntegerField(label="Enter a number") class MyPage(Page): form_model = 'player' form_fields = ['number'] class Results(Page): @staticmethod def vars_for_template(player: Player): return dict(me_in_all_rounds=player.in_all_rounds()) page_sequence = [MyPage, Results] history_table / Results.html From otree - snippets {{block title}} History {{endblock}} {{block content}} < table class ="table" > < tr > < th > Round < / th > < th > Number < / th > < / tr > {{ for p in me_in_all_rounds}} < tr > < td > {{p.round_number}} < / td > < td > {{p.number}} < / td > < / tr > {{endfor}} < / table > {{next_button}} {{endblock}} history_table / MyPage.html From otree - snippets {{block title}} Enter a number {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} sequential_symmetric / table.html From otree - snippets {{ if players}} < table class ="table" style="width: auto" > < tr > < th > Player < / th > < th > Guess < / th > < / tr > {{ for p in players}} < tr > < td > Player {{p.id_in_group}} < / td > < td > {{p.decision}} < / td > < / tr > {{endfor}} < / table > {{endif}} sequential_symmetric / __init__.py From otree - snippets from otree.api import * doc = """ Sequential / cascade game (symmetric). Also see "intergenerational" featured app. """ class C(BaseConstants): NAME_IN_URL = 'sequential_symmetric' PLAYERS_PER_GROUP = 3 NUM_ROUNDS = 1 MAIN_TEMPLATE = __name__ + '/Decide.html' FORM_FIELDS = ['decision'] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): decision = models.IntegerField( label="How many countries are there in Africa? (Make your best guess)" ) def vars_for_template1(player: Player): return dict( # get the players whose ID is less than mine players=[ p for p in player.get_others_in_group() if p.id_in_group < player.id_in_group ] ) # PAGES class P1(Page): form_model = 'player' form_fields = C.FORM_FIELDS template_name = C.MAIN_TEMPLATE @staticmethod def is_displayed(player: Player): return player.id_in_group == 1 vars_for_template = vars_for_template1 class WaitPage1(WaitPage): pass class P2(Page): form_model = 'player' form_fields = C.FORM_FIELDS template_name = C.MAIN_TEMPLATE @staticmethod def is_displayed(player: Player): return player.id_in_group == 2 vars_for_template = vars_for_template1 class WaitPage2(WaitPage): pass class P3(Page): form_model = 'player' form_fields = C.FORM_FIELDS template_name = C.MAIN_TEMPLATE @staticmethod def is_displayed(player: Player): return player.id_in_group == 3 vars_for_template = vars_for_template1 class WaitPage3(WaitPage): pass class Results(Page): @staticmethod def vars_for_template(player: Player): group = player.group return dict(players=group.get_players()) page_sequence = [P1, WaitPage1, P2, WaitPage2, P3, WaitPage3, Results] sequential_symmetric / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > Here are the results.(You are player {{player.id_in_group}}.) < / p > {{include_sibling 'table.html'}} {{endblock}} sequential_symmetric / Decide.html From otree - snippets {{block content}} < ul > < li > This is a sequential game with {{C.PLAYERS_PER_GROUP}} players.< / li > < li > You are player {{player.id_in_group}}. < / li > < li > Each player will see the previous player 's choices < / ul > {{include_sibling 'table.html'}} {{formfields}} {{next_button}} {{endblock}} redirect_to_other_website / Redirect.html From otree - snippets {{block title}} Redirecting... {{endblock}} {{block content}} < script > window.location.href = js_vars.redirect_url; < / script > {{endblock}} redirect_to_other_website / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'redirect_to_other_website' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): citizenship = models.StringField() class MyPage(Page): form_model = 'player' form_fields = ['citizenship'] class Redirect(Page): @staticmethod def js_vars(player: Player): # google is just an example. you should change this to qualtrics or whatever survey provider # you are using. return dict(redirect_url='https://www.google.com/search?q=' + player.citizenship) page_sequence = [MyPage, Redirect] redirect_to_other_website / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{formfields}} < p > < i > After the user clicks 'next', they will be directed to another website. We append the user 's data to the URL, for example: < code > google.com / search?q = Canada < / code > < / i > < / p > {{next_button}} {{endblock}} multi_select / __init__.py From otree - snippets from otree.api import * doc = """ Question that lets you select multiple options (multi-select, multiple choice / multiple answer) """ class C(BaseConstants): NAME_IN_URL = 'select_multiple' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 LANGUAGES = ['english', 'german', 'french', 'spanish', 'italian', 'chinese'] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): english = models.BooleanField(blank=True) german = models.BooleanField(blank=True) french = models.BooleanField(blank=True) spanish = models.BooleanField(blank=True) italian = models.BooleanField(blank=True) chinese = models.BooleanField(blank=True) # PAGES class MyPage(Page): form_model = 'player' form_fields = C.LANGUAGES page_sequence = [MyPage] multi_select / MyPage.html From otree - snippets {{block content}} < p > What languages do you speak? Select all that apply. < / p > {{ for field in C.LANGUAGES}} < label > < input type = "checkbox" name = "{{ field }}" value = "1" > {{field}} < / label > < br > {{endfor}} < p > {{next_button}} < / p > {{endblock}} complex_form_layout / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'complex_form_layout' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): a1 = models.IntegerField() a2 = models.IntegerField() a3 = models.IntegerField() a4 = models.IntegerField() b1 = models.StringField() b2 = models.StringField() b3 = models.StringField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3'] @staticmethod def vars_for_template(player: Player): import random a_fields = ['a1', 'a2', 'a3', 'a4'] b_fields = ['b1', 'b2', 'b3'] random.shuffle(a_fields) random.shuffle(b_fields) return dict(a_fields=a_fields, b_fields=b_fields) page_sequence = [MyPage] complex_form_layout / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > < i > fields are in 2 sections, and randomized within a section. < / i > < / p > < p > Please answer the following questions about topic A < / p > {{ for field in a_fields}} {{formfield field}} {{endfor}} < p > Please answer the following questions about topic B < / p > {{ for field in b_fields}} {{formfield field}} {{endfor}} {{next_button}} {{endblock}} rank_widget / __init__.py From otree - snippets from otree.api import * doc = """ "Widget to rank/reorder items". See http://sortablejs.github.io/Sortable/ for more examples. """ class C(BaseConstants): NAME_IN_URL = 'rank_widget' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 CHOICES = ['Martini', 'Margarita', 'White Russian', 'Pina Colada', 'Gin & Tonic'] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): ranking = models.StringField() class MyPage(Page): form_model = 'player' form_fields = ['ranking'] class Results(Page): pass page_sequence = [MyPage, Results] rank_widget / Results.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > Your ranking is: {{player.ranking}} < / p > {{next_button}} {{endblock}} rank_widget / MyPage.html From otree - snippets {{block title}} Rank your favorite drinks {{endblock}} {{block content}} < ul id = "items" class ="list-group list-group-numbered" style="cursor: move" > {{ for choice in C.CHOICES}} < li data - id = "{{ choice }}" class ="list-group-item" > {{choice}} < / li > {{endfor}} < / ul > < script src = "https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js" > < / script > < script > let el = document.getElementById('items'); let sortable = Sortable.create(el, { onChange: function(evt) { document.getElementById('ranking').value = sortable.toArray().join(','); } }); < / script > < input type = "hidden" name = "ranking" id = "ranking" > {{formfield_errors 'ranking'}} < p > {{next_button}} < / p > {{endblock}} question_with_other_option / __init__.py From otree - snippets from otree.api import * doc = """ Menu with an 'other' option that lets you type in a valueInput manually """ class C(BaseConstants): NAME_IN_URL = 'question_with_other_option' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): native_language = models.StringField( choices=['German', 'English', 'Chinese', 'Turkish', 'Other'] ) native_language_other = models.StringField( label="You selected 'other'. What is your native language?" ) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['native_language'] class MyPage2(Page): @staticmethod def is_displayed(player: Player): return player.native_language == 'Other' form_model = 'player' form_fields = ['native_language_other'] page_sequence = [MyPage, MyPage2] question_with_other_option / MyPage2.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} question_with_other_option / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} wait_page_timeout / Task.html From otree - snippets {{block title}} Task {{endblock}} {{block content}} < p > Continue the experiment... < / p > {{next_button}} {{endblock}} wait_page_timeout / __init__.py From otree - snippets from otree.api import * doc = """Timeout on a WaitPage (exit the experiment)""" class C(BaseConstants): NAME_IN_URL = 'wait_page_timeout' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 TIMEOUT = 15 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): import random for p in subsession.get_players(): p.completion_code = random.randint(10 ** 6, 10 ** 7) class Group(BaseGroup): pass class Player(BasePlayer): timeout = models.FloatField() completion_code = models.IntegerField() # PAGES class MyPage(Page): @staticmethod def before_next_page(player: Player, timeout_happened): import time # 15 seconds on wait page max player.timeout = time.time() + C.TIMEOUT class ResultsWaitPage(WaitPage): template_name = 'wait_page_timeout/ResultsWaitPage.html' @staticmethod def js_vars(player: Player): return dict(timeout=C.TIMEOUT) @staticmethod def vars_for_template(player: Player): import time timeout_happened = time.time() > player.timeout return dict(timeout_happened=timeout_happened) class Task(Page): pass page_sequence = [MyPage, ResultsWaitPage, Task] wait_page_timeout / MyPage.html From otree - snippets {{block title}} Welcome {{endblock}} {{block content}} < p > Press next to continue ... < / p > {{next_button}} {{endblock}} wait_page_timeout / ResultsWaitPage.html From otree - snippets {{extends 'otree/WaitPage.html'}} {{block title}} Please wait {{endblock}} {{block content}} {{ if timeout_happened}} < p > No other players showed up in time. Please submit this HIT with completion code < b > {{player.completion_code}} < / b > < / p > {{ else}} < p > If you are left waiting for longer than {{C.TIMEOUT}} seconds, the game will end. < / p > < script > setInterval(function() { window.location.reload(); }, js_vars.timeout * 1000); < / script > {{endif}} {{endblock}} detect_mobile / Task.html From otree - snippets {{block title}} Task. {{endblock}} {{block content}} < p > You are not using a mobile browser, so you can continue.< / p > {{next_button}} {{endblock}} detect_mobile / __init__.py From otree - snippets from otree.api import * doc = """Detect and block mobile browsers""" class C(BaseConstants): NAME_IN_URL = 'detect_mobile' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): is_mobile = models.BooleanField() # PAGES class MobileCheck(Page): form_model = 'player' form_fields = ['is_mobile'] def error_message(player: Player, values): if values['is_mobile']: return "Sorry, this experiment does not allow mobile browsers." class Task(Page): pass page_sequence = [MobileCheck, Task] detect_mobile / MobileCheck.html From otree - snippets {{block title}} Start {{endblock}} {{block content}} < input type = "hidden" name = "is_mobile" id = "is_mobile" > < p > Please click next. < / p > {{next_button}} < script > function isMobile() { const toMatch = [ / Android / i, / iPhone / i, / iPad / i, ]; return toMatch.some((item) = > navigator.userAgent.match(item)); } // here is an alternative technique that checks screen resolution // function isMobile() { // return ((window.innerWidth <= 800) & & (window.innerHeight <= 600)); //} document.getElementById('is_mobile').value = isMobile() ? 1: 0; < / script > {{endblock}} gbat_fallback_solo_task_part1 / __init__.py From otree - snippets from otree.api import * doc = """group_by_arrival_time timeout (continue with solo task)""" class C(BaseConstants): NAME_IN_URL = 'gbat_fallback_solo_task_part1' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def group_by_arrival_time_method(subsession, waiting_players): print('waiting_players', waiting_players) if len(waiting_players) >= 2: return waiting_players[:2] for player in waiting_players: if waiting_too_long(player): # make a single-player group. print('waiting too long, making 1 player group') return [player] class Group(BaseGroup): pass class Player(BasePlayer): favorite_color = models.StringField() def waiting_too_long(player: Player): participant = player.participant import time # assumes you set wait_page_arrival in PARTICIPANT_FIELDS. return time.time() - participant.wait_page_arrival > 60 class GBAT(WaitPage): group_by_arrival_time = True @staticmethod def app_after_this_page(player: Player, upcoming_apps): # if it's a solo group (1 player), skip this app # and go to the next app (which in this case is a # single-player task) if len(player.get_others_in_group()) == 0: return upcoming_apps[0] class GroupTask(Page): form_model = 'player' form_fields = ['favorite_color'] class MyWait(WaitPage): pass class Results(Page): pass page_sequence = [GBAT, GroupTask, MyWait, Results] gbat_fallback_solo_task_part1 / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > The colors chosen in your group were: < / p > < ul > {{ for p in group.get_players()}} < li > {{p.favorite_color}} < / li > {{endfor}} < / ul > {{next_button}} {{endblock}} gbat_fallback_solo_task_part1 / GroupTask.html From otree - snippets {{block content}} < p > Your game goes here... < / p > {{formfields}} {{next_button}} {{endblock}} gbat_fallback_smaller_group_part0 / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'gbat_fallback_smaller_group_part0' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class MyPage(Page): @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant import time participant.wait_page_arrival = time.time() page_sequence = [MyPage] gbat_fallback_smaller_group_part0 / MyPage.html From otree - snippets {{block title}} Welcome {{endblock}} {{block content}} < p > Welcome! Please press next. You will be placed in a group of 4. However, if not enough players show up, a smaller group may be formed with whoever is available. < / p > {{next_button}} {{endblock}} chat_from_scratch / __init__.py From otree - snippets from otree.api import * doc = """ Of course oTree has a readymade chat widget described here: https://otree.readthedocs.io/en/latest/multiplayer/chat.html But you can use this if you want a chat box that is more easily customizable, or if you want programmatic access to the chat messages. This app can also help you learn about live pages in general. """ class C(BaseConstants): NAME_IN_URL = 'chat_from_scratch' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class Message(ExtraModel): group = models.Link(Group) sender = models.Link(Player) text = models.StringField() def to_dict(msg: Message): return dict(sender=msg.sender.id_in_group, text=msg.text) # PAGES class MyPage(Page): @staticmethod def js_vars(player: Player): return dict(my_id=player.id_in_group) @staticmethod def live_method(player: Player, data): my_id = player.id_in_group group = player.group if 'text' in data: text = data['text'] msg = Message.create(group=group, sender=player, text=text) return {0: [to_dict(msg)]} return {my_id: [to_dict(msg) for msg in Message.filter(group=group)]} page_sequence = [MyPage] chat_from_scratch / chat.html From otree - snippets < div id = "chat_messages" > < / div > < div > < input type = "text" id = "chat_input" > < button type = "button" onclick = "sendMsg()" > Send < / button > < / div > < script > let chat_input = document.getElementById('chat_input'); chat_input.addEventListener("keydown", function(event) { if (event.key === "Enter") { sendMsg(); } }); function sendMsg() { let text = chat_input.value.trim(); if (text) { liveSend({'text': text}); } chat_input.value = ''; } let chat_messages = document.getElementById('chat_messages'); function liveRecv(messages) { for (let msg of messages) { let msgSpan = document.createElement('span'); msgSpan.textContent = msg.text; let sender = msg.sender == = js_vars.my_id ? 'Me': `Player ${msg.sender} `; let row = ` < div > < b >${sender} < / b >: ${msgSpan.innerHTML} < / div > `; chat_messages.insertAdjacentHTML('beforeend', row); } } document.addEventListener("DOMContentLoaded", function(event) { liveSend({}); }); < / script > chat_from_scratch / MyPage.html From otree - snippets {{block content}} {{include_sibling 'chat.html'}} {{endblock}} are_you_sure / __init__.py From otree - snippets from otree.api import * doc = """ 'Are you sure?' popup based on the user's input """ class C(BaseConstants): NAME_IN_URL = 'are_you_sure' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): contribution = models.CurrencyField( min=0, max=100, label="How much of your 100 points do you want to contribute?" ) reason = models.LongStringField( blank=True, label="Please write a message to your teammates explaining your decision", ) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['contribution', 'reason'] page_sequence = [MyPage] are_you_sure / MyPage.html From otree - snippets {{block content}} < p > < i > This page warns if the user contributes 0 or their explanation is too short. < / i > < / p > {{formfields}} < button type = "button" class ="btn btn-primary" onclick="checkSubmit()" > Next < / button > < script > function checkSubmit() { let form = document.getElementById('form'); let isValid = form.reportValidity(); if (!isValid) return; let warnings = []; let contribution = document.getElementsByName('contribution')[0].value; if (contribution === '0') { warnings.push("Are you sure you don't want to contribute anything?"); } let reason = document.getElementsByName('reason')[0].value; if (reason.length < 10) { warnings.push("Are you sure you don't want to give a longer explanation?") } if (warnings.length > 0) { warnings.push("Press OK to proceed anyway.") let confirmed = window.confirm(warnings.join('\r\n')); if (!confirmed) return; } form.submit(); } < / script > {{endblock}} longitudinal / Bridge.html From otree - snippets {{block content}} < p > Thank you for participating in part 1. < / p > < p > Please come back after < b > {{player.part2_start_time_readable}} < / b > to take part in the next phase. < / p > {{endblock}} longitudinal / Part1.html From otree-snippets {{block title}} Survey {{endblock}} {{block content}} < p > < i > The first phase of your experiment goes here...< / i > < / p > {{formfields}} {{next_button}} {{endblock}} longitudinal / __init__.py From otree-snippets from otree.api import * doc = """ Longitudinal study (2-part study taking place across days/weeks) Another way to do longitudinal studies is just to give participants a Room URL. Since that URL is persistent, you can create a new session when the next phase has begun. But the technique here has the advantage of storing both phases together in a single session. For example, you can easily compare the user's answer to their answer in the previous phase. """ class C(BaseConstants): NAME_IN_URL = 'longitudinal' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): question = models.StringField() part2_start_time = models.FloatField() part2_start_time_readable = models.StringField() # PAGES class Part1(Page): @staticmethod def before_next_page(player: Player, timeout_happened): from datetime import datetime, timedelta t = datetime.now() + timedelta(weeks=1) # or can make it for a specific date: # start = datetime.strptime('2022-07-15', '%Y-%m-%d') # .timestamp() gives you an integer (a.k.a. 'epoch time') player.part2_start_time = t.timestamp() # print('player.part2_start_time is', player.part2_start_time) # this gives you a formatted date you can display to users player.part2_start_time_readable = t.strftime('%A, %B %d') def still_waiting_for_part_2(player: Player): import time # returns True if the current time is before the designated start time return time.time() < player.part2_start_time class Bridge(Page): """ If the user arrives at this page after part 2 is ready, this page will be skipped entirely. """ @staticmethod def is_displayed(player: Player): return still_waiting_for_part_2(player) @staticmethod def before_next_page(player: Player, timeout_happened): return "Player somehow tried to proceed past a page with no next button" class Part2(Page): pass page_sequence = [Part1, Bridge, Part2] longitudinal / Part2.html From otree - snippets {{block title}} Survey {{endblock}} {{block content}} < p > < i > The second phase of your experiment goes here... < / i > < / p > {{formfields}} {{next_button}} {{endblock}} comprehension_test_simple / __init__.py From otree - snippets from otree.api import * doc = """ Simple version of comprehension test """ class C(BaseConstants): NAME_IN_URL = 'comprehension_test_simple' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): quiz1 = models.IntegerField(label='What is 2 + 2?') quiz2 = models.IntegerField(label="What year did COVID-19 start?") quiz3 = models.BooleanField(label="Is 9 a prime number?") class MyPage(Page): form_model = 'player' form_fields = ['quiz1', 'quiz2', 'quiz3'] @staticmethod def error_message(player: Player, values): solutions = dict(quiz1=4, quiz2=2019, quiz3=False) if values != solutions: return "One or more answers were incorrect." class Results(Page): pass page_sequence = [MyPage, Results] comprehension_test_simple / Results.html From otree - snippets {{block title}} Thank you {{endblock}} {{block content}} < p > You answered all questions correctly < / p > {{endblock}} comprehension_test_simple / MyPage.html From otree - snippets {{block title}} Comprehension test {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} random_num_rounds / End.html From otree - snippets {{block title}} End {{endblock}} {{block content}} The session is finished. {{endblock}} random_num_rounds / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'random_num_rounds' PLAYERS_PER_GROUP = None NUM_ROUNDS = 20 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): import random for p in subsession.get_players(): p.participant.num_rounds = random.randint(1, 20) class Group(BaseGroup): pass class Player(BasePlayer): num_rounds = models.IntegerField() # PAGES class MyPage(Page): @staticmethod def is_displayed(player: Player): """ Skip this page if the round number has exceeded the participant's designated number of rounds. """ participant = player.participant return player.round_number < participant.num_rounds class End(Page): @staticmethod def is_displayed(player: Player): return player.round_number == C.NUM_ROUNDS page_sequence = [MyPage, End] random_num_rounds / MyPage.html From otree - snippets {{block title}} Round {{subsession.round_number}} {{endblock}} {{block content}} < p > This player will continue for {{participant.num_rounds}} rounds. < / p > {{next_button}} {{endblock}} persist_raw / __init__.py From otree - snippets from otree.api import * doc = """ Sliders and checkboxes that don't get wiped out on form reload. Also works for text/number inputs, etc. """ class C(BaseConstants): NAME_IN_URL = 'persist_raw' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): f_int = models.IntegerField(min=10) f_bool1 = models.BooleanField(blank=True) f_bool2 = models.BooleanField(blank=True) f_bool3 = models.BooleanField(blank=True) f_bool4 = models.BooleanField(blank=True) f_bool5 = models.BooleanField(blank=True) # PAGES class MyPage(Page): form_model = 'player' form_fields = [ 'f_int', 'f_bool1', 'f_bool2', 'f_bool3', 'f_bool4', 'f_bool5', ] page_sequence = [MyPage] persist_raw / MyPage.html From otree - snippets {{block content}} < p > If you 've used raw HTML widgets (slider/checkbox), you may have noticed that they are wiped out on when the form is re - rendered to show errors. This page contains simple code to overcome that limitation. < / p > < p > To test, modify the form fields, then submit the page. (The form will fail validation until you set the slider to the correct value.) < / p > < label class ="col-form-label" > Here is a slider: < / label > < div style = "display: flex" > 0 & nbsp; < input type = "range" name = "f_int" min = "0" max = "10" style = "flex: 1" class ="persist" > & nbsp; 10 < / div > {{formfield_errors 'f_int'}} < br > < p > Here are some checkboxes: < / p > < input type = "checkbox" name = "f_bool1" value = "1" class ="persist" > < input type = "checkbox" name = "f_bool2" value = "1" class ="persist" > < input type = "checkbox" name = "f_bool3" value = "1" class ="persist" > < input type = "checkbox" name = "f_bool4" value = "1" class ="persist" > < input type = "checkbox" name = "f_bool5" value = "1" class ="persist" > < br > < br > {{next_button}} { # INSTRUCTIONS (1) make sure your _static / folder contains persist - raw.js (2) copy the below 'script' tag into your template (2) add class ="persist" to your raw HTML inputs # } < script src = "{{ static 'persist-raw.js' }}" > < / script > {{endblock}} dropout_end_game / DropoutHappened.html From otree - snippets {{block content}} < p > A player in your group dropped out. Therefore, you will be forwarded to the next app. < / p > {{next_button}} {{endblock}} dropout_end_game / DropoutTest.html From otree - snippets {{block title}} Dropout check {{endblock}} {{block content}} < p > Important: click "next" before the timeout occurs. Otherwise you will be considered a dropout. < / p > {{next_button}} {{endblock}} dropout_end_game / __init__.py From otree - snippets from otree.api import * doc = """ Dropout detection for multiplayer game (end the game) """ class C(BaseConstants): NAME_IN_URL = 'dropout_end_game' PLAYERS_PER_GROUP = None NUM_ROUNDS = 5 class Subsession(BaseSubsession): pass class Group(BaseGroup): has_dropout = models.BooleanField(initial=False) class Player(BasePlayer): is_dropout = models.BooleanField() class Game(Page): timeout_seconds = 10 class DropoutTest(Page): timeout_seconds = 10 @staticmethod def before_next_page(player: Player, timeout_happened): group = player.group if timeout_happened: group.has_dropout = True player.is_dropout = True class WaitForOthers(WaitPage): pass class DropoutHappened(Page): @staticmethod def is_displayed(player: Player): group = player.group return group.has_dropout @staticmethod def app_after_this_page(player: Player, upcoming_apps): return upcoming_apps[0] page_sequence = [Game, DropoutTest, WaitForOthers, DropoutHappened] dropout_end_game / Game.html From otree - snippets {{block title}} Game, round {{subsession.round_number}} {{endblock}} {{block content}} < p > < i > Your game goes here... < / i > < / p > {{formfields}} {{next_button}} {{endblock}} configurable_players_per_group / __init__.py From otree - snippets from otree.api import * doc = """ Configurable players per group. See here: https://otree.readthedocs.io/en/latest/treatments.html#configure-sessions """ class C(BaseConstants): NAME_IN_URL = 'configurable_players_per_group' # Since Constants does not have access to the session config, # (it is loaded when the server starts, rather than for each session) # we set the groups manually inside creating_session. PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): session = subsession.session ppg = session.config['players_per_group'] players = subsession.get_players() matrix = [] for i in range(0, len(players), ppg): matrix.append(players[i: i + ppg]) # print('matrix is', matrix) subsession.set_group_matrix(matrix) class Group(BaseGroup): pass class Player(BasePlayer): pass class MyPage(Page): pass page_sequence = [MyPage] configurable_players_per_group / MyPage.html From otree - snippets image_choices / __init__.py From otree - snippets from otree.api import * doc = """ Images in radio button choices """ def make_image_data(image_names): return [dict(name=name, path='shapes/{}'.format(name)) for name in image_names] class C(BaseConstants): NAME_IN_URL = 'image_choices' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): img_choice = models.StringField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['img_choice'] @staticmethod def vars_for_template(player: Player): image_names = [ 'circle-blue.svg', 'plus-green.svg', 'star-red.svg', 'triangle-yellow.svg', ] return dict(image_data=make_image_data(image_names)) page_sequence = [MyPage] image_choices / MyPage.html From otree - snippets {{block content}} < p > Choose your favorite image. < / p > {{ for image in image_data}} < label style = "text-align: center" > < img src = "{{ static image.path }}" width = "200px" > < br > < input type = "radio" name = "img_choice" value = "{{ image.name }}" class ="persist" > < / label > {{endfor}} {{formfield_errors 'img_choice'}} < br > {{next_button}} < script src = "{{ static 'persist-raw.js' }}" > < / script > {{endblock}} pay_random_round / __init__.py From otree - snippets from otree.api import * doc = """ Select a random round for payment """ class C(BaseConstants): NAME_IN_URL = 'pay_random_round' PLAYERS_PER_GROUP = None NUM_ROUNDS = 4 ENDOWMENT = cu(100) class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): give_amount = models.CurrencyField( min=0, max=100, label="How much do you want to give?" ) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['give_amount'] @staticmethod def before_next_page(player: Player, timeout_happened): import random participant = player.participant # if it's the last round if player.round_number == C.NUM_ROUNDS: random_round = random.randint(1, C.NUM_ROUNDS) participant.selected_round = random_round player_in_selected_round = player.in_round(random_round) player.payoff = C.ENDOWMENT - player_in_selected_round.give_amount class Results(Page): @staticmethod def is_displayed(player: Player): return player.round_number == C.NUM_ROUNDS page_sequence = [MyPage, Results] pay_random_round / Results.html From otree - snippets {{block content}} {{ if subsession.round_number == C.NUM_ROUNDS}} < p > Round {{participant.selected_round}} was randomly selected for payment. Your final payoff is therefore {{player.payoff}}. < / p > {{endif}} {{endblock}} pay_random_round / MyPage.html From otree - snippets {{block title}} Round {{subsession.round_number}} {{endblock}} {{block content}} < p > You have {{C.ENDOWMENT}} to split between you and another player. < / p > {{formfields}} {{next_button}} {{endblock}} quiz_with_explanation / __init__.py From otree - snippets from otree.api import * doc = """ Quiz with explanation. Re-display the previous page's form as read-only, with answers/explanation. """ class C(BaseConstants): NAME_IN_URL = 'quiz_with_explanation' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 def get_quiz_data(): return [ dict( name='a', solution=True, explanation="3 is prime. It has no factorization other than 1 and itself.", ), dict( name='b', solution=False, explanation="2 + 2 is 4.", ), ] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): a = models.BooleanField(label="Is 3 a prime number?") b = models.IntegerField(label="What is 2 + 2?") class MyPage(Page): form_model = 'player' form_fields = ['a', 'b'] @staticmethod def vars_for_template(player: Player): fields = get_quiz_data() return dict(fields=fields, show_solutions=False) class Results(Page): form_model = 'player' form_fields = ['a', 'b'] @staticmethod def vars_for_template(player: Player): fields = get_quiz_data() # we add an extra entry 'is_correct' (True/False) to each field for d in fields: d['is_correct'] = getattr(player, d['name']) == d['solution'] return dict(fields=fields, show_solutions=True) @staticmethod def error_message(player: Player, values): for field in values: if getattr(player, field) != values[field]: return "A field was somehow changed but this page is read-only." page_sequence = [MyPage, Results] quiz_with_explanation / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < style > / * interestingly, 'readonly' doesn 't apply to radio buttons. so we set 'pointer-events: none' to prevent clicking a radio. (it can also be done through JS but doesn't hurt to have this extra measure) (note: radio buttons can also be changed using the keyboard) note: we don 't set ' disabled ' because disabled inputs don' t get submitted by the form, and therefore the server would complain that the form is missing. * / input, label { pointer - events: none; } .solution - incorrect { color: red; } .solution - correct { color: green; } < / style > < p > Here are your answers along with the solutions.< / p > {{include_sibling 'form.html'}} {{next_button}} < script > // for (let input of document.getElementsByTagName('input')) { input.readOnly = true; } // workaround for radio buttons.disable all radio buttons that aren't already checked. // this prevents changing a radio. $(':radio:not(:checked)').attr('disabled', true); < / script > {{endblock}} quiz_with_explanation / MyPage.html From otree-snippets {{block title}} Quiz {{endblock}} {{block content}} {{include_sibling 'form.html'}} {{next_button}} {{endblock}} quiz_with_explanation / form.html From otree-snippets {{for d in fields}} {{formfield d.name}} {{if show_solutions}} {{if d.is_correct}} < p class ="solution-correct" > Correct. < / p > {{ else}} < p class ="solution-incorrect" > {{d.explanation}} < / p > {{endif}} {{endif}} {{endfor}} gbat_keep_same_groups_part0 / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'gbat_keep_same_groups_part0' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): pass page_sequence = [MyPage] gbat_keep_same_groups_part0 / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > < i > This would just be the first app that appears first in the app sequence, to filter out some users before doing group_by_arrival_time. Maybe it asks for their consent, or has them do some real-effort task, to filter out people who are likely to drop out. < / i > < / p > {{next_button}} {{endblock}} sequential / __init__.py From otree - snippets from otree.api import * doc = """ Sequential game (asymmetric) """ class C(BaseConstants): NAME_IN_URL = 'sequential' PLAYERS_PER_GROUP = 3 NUM_ROUNDS = 1 MAIN_TEMPLATE = __name__ + '/Decide.html' class Subsession(BaseSubsession): pass class Group(BaseGroup): mixer = models.StringField( choices=['Pineapple juice', 'Orange juice', 'Cola', 'Milk'], label="Choose a mixer", widget=widgets.RadioSelect, ) liqueur = models.StringField( choices=['Blue curacao', 'Triple sec', 'Amaretto', 'Kahlua'], label="Choose a liqueur", widget=widgets.RadioSelect, ) spirit = models.StringField( choices=['Vodka', 'Rum', 'Gin', 'Tequila'], label="Choose a spirit", widget=widgets.RadioSelect, ) class Player(BasePlayer): pass # PAGES class P1(Page): form_model = 'group' form_fields = ['mixer'] template_name = C.MAIN_TEMPLATE @staticmethod def is_displayed(player: Player): return player.id_in_group == 1 class WaitPage1(WaitPage): pass class P2(Page): form_model = 'group' form_fields = ['liqueur'] template_name = C.MAIN_TEMPLATE @staticmethod def is_displayed(player: Player): return player.id_in_group == 2 class WaitPage2(WaitPage): pass class P3(Page): form_model = 'group' form_fields = ['spirit'] template_name = C.MAIN_TEMPLATE @staticmethod def is_displayed(player: Player): return player.id_in_group == 3 class WaitPage3(WaitPage): pass class Results(Page): @staticmethod def vars_for_template(player: Player): group = player.group return dict(players_with_contributions=group.get_players()) page_sequence = [P1, WaitPage1, P2, WaitPage2, P3, WaitPage3, Results] sequential / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > The cocktail consists of {{group.mixer}}, {{group.liqueur}}, and {{group.spirit}} < / p > {{endblock}} sequential / Decide.html From otree - snippets {{block title}} Make a cocktail! {{endblock}} {{block content}} < ul > < li > This is a sequential game with {{C.PLAYERS_PER_GROUP}} players.< / li > < li > You are player {{player.id_in_group}}. < / li > < li > The objective is to make a cocktail with 3 ingredients.Each player chooses one ingredient.< / li > < / ul > {{ if player.id_in_group >= 2}} < p > Player 1 chose {{group.mixer}}. < / p > {{endif}} {{ if player.id_in_group >= 3}} < p > Player 2 chose {{group.liqueur}}. < / p > {{endif}} {{formfields}} {{next_button}} {{endblock}} comprehension_test_complex / Failed.html From otree - snippets {{block content}} Sorry, you gave too many wrong answers to the comprehension test. {{endblock}} comprehension_test_complex / __init__.py From otree - snippets from otree.api import * doc = """ Comprehension test. If the user fails too many times, they exit. """ class C(BaseConstants): NAME_IN_URL = 'comprehension_test_complex' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): num_failed_attempts = models.IntegerField(initial=0) failed_too_many = models.BooleanField(initial=False) quiz1 = models.IntegerField(label='What is 2 + 2?') quiz2 = models.StringField( label='What is the capital of Canada?', choices=['Ottawa', 'Toronto', 'Vancouver'], ) quiz3 = models.IntegerField(label="What year did COVID-19 start?") quiz4 = models.BooleanField(label="Is 9 a prime number") class MyPage(Page): form_model = 'player' form_fields = ['quiz1', 'quiz2', 'quiz3', 'quiz4'] @staticmethod def error_message(player: Player, values): # alternatively, you could make quiz1_error_message, quiz2_error_message, etc. # but if you have many similar fields, this is more efficient. solutions = dict(quiz1=4, quiz2='Ottawa', quiz3=2019, quiz4=False) # error_message can return a dict whose keys are field names and whose # values are error messages errors = {name: 'Wrong' for name in solutions if values[name] != solutions[name]} # print('errors is', errors) if errors: player.num_failed_attempts += 1 if player.num_failed_attempts >= 3: player.failed_too_many = True # we don't return any error here; just let the user proceed to the # next page, but the next page is the 'failed' page that boots them # from the experiment. else: return errors class Failed(Page): @staticmethod def is_displayed(player: Player): return player.failed_too_many class Results(Page): pass page_sequence = [MyPage, Failed, Results] comprehension_test_complex / Results.html From otree - snippets {{block title}} Thank you {{endblock}} {{block content}} < p > You answered all questions correctly < / p > {{endblock}} comprehension_test_complex / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} pass_data_between_apps_part2 / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'pass_data_between_apps2' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): pass page_sequence = [MyPage] pass_data_between_apps_part2 / MyPage.html From otree - snippets {{block title}} App 2 {{endblock}} {{block content}} < p > In the previous app, you said your main language is < b > {{participant.language}} < / b >. < / p > {{endblock}} rank_players / __init__.py From otree - snippets from otree.api import * doc = """ Rank players """ class C(BaseConstants): NAME_IN_URL = 'rank_players' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): age = models.IntegerField(label="Enter your age") rank = models.IntegerField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['age'] class ResultsWaitPage(WaitPage): @staticmethod def after_all_players_arrive(group: Group): players = group.get_players() # to do descending, use -p.age players.sort(key=lambda p: p.age) for i in range(len(players)): # this code checks if there is a tie and then assigns the same rank # if you don't need to deal with ties, then you can delete this. if i > 0 and players[i].age == players[i - 1].age: rank = players[i - 1].rank else: rank = i + 1 players[i].rank = rank class Results(Page): @staticmethod def vars_for_template(player: Player): group = player.group return dict(num_players=len(group.get_players())) page_sequence = [MyPage, ResultsWaitPage, Results] rank_players / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > Your age is {{player.age}}. In your group of {{num_players}} players, your rank is {{player.rank}} (youngest to oldest). < / p > {{endblock}} rank_players / MyPage.html From otree - snippets {{block content}} {{formfields}} {{next_button}} {{endblock}} placeholder / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'placeholder' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): pass page_sequence = [MyPage] placeholder / MyPage.html From otree - snippets {{block title}} Placeholder {{endblock}} {{block content}} < p > < i > This app is just a placeholder. < / i > < / p > {{endblock}} groups_csv / __init__.py From otree - snippets from otree.api import * doc = """ Reads groups from a CSV file. Inside this app, you will find a groups6.csv, which defines the groups in the case where there are 6 players. You can edit the file in Excel, or in plain text. In the below example, there are 5 rows, defining 5 rounds. In each row, empty cells are used to separate groups. So, in round 1, there are 3 groups: players 1&4, 2&5, 3&6: 1,4,,2,5,,3,6 1,2,,3,4,,6,5 1,3,,6,2,,5,4 1,6,,5,3,,4,2 1,5,,4,6,,2,3 If you want to create a session with a different number of players, such as 12, you would need to create a file called groups12.csv. """ def make_group(comma_delim_string): return [int(x) for x in comma_delim_string.split(',')] class C(BaseConstants): NAME_IN_URL = 'groups_csv' PLAYERS_PER_GROUP = None NUM_ROUNDS = 5 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # FUNCTIONS def creating_session(subsession: Subsession): session = subsession.session if subsession.round_number == 1: num_participants = session.num_participants fn = 'groups_csv/groups{}.csv'.format(num_participants) with open(fn) as f: matrices = [] for line in f: line = line.strip() group_specs = line.split(',,') matrix = [make_group(spec) for spec in group_specs] matrices.append(matrix) session.matrices = matrices this_round_matrix = session.matrices[subsession.round_number - 1] subsession.set_group_matrix(this_round_matrix) # print('this_round_matrix', this_round_matrix) # PAGES class MyPage(Page): pass page_sequence = [ MyPage, ] groups_csv / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > No content here; this app is just to demonstrate group shuffling (look at the groups in the admin interface). < / p > {{next_button}} {{endblock}} radio_switching_point / __init__.py From otree - snippets from otree.api import * doc = """ Table where each row has a left/right choice, like the strategy method. This app enforces a single switching point """ class C(BaseConstants): NAME_IN_URL = 'radio_switching_point' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): left_side_amount = models.IntegerField(initial=10) switching_point = models.IntegerField() # PAGES class Decide(Page): form_model = 'player' form_fields = ['switching_point'] @staticmethod def vars_for_template(player: Player): return dict(right_side_amounts=range(10, 21, 1)) class Results(Page): pass page_sequence = [Decide, Results] radio_switching_point / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > Your switching point was {{player.switching_point}} < / p > {{endblock}} radio_switching_point / Decide.html From otree - snippets {{block title}} Choose a value for each row {{endblock}} {{block content}} < input type = "hidden" name = "switching_point" id = "id_switching_point" > {{formfield_errors 'switching_point'}} < table class ="table table-striped" > < colgroup > < col width = "45%" > < col width = "10%" > < col width = "45%" > < / colgroup > < tr > < td align = "right" > < b > Option A < / b > < / td > < td > < / td > < td align = "left" > < b > Option B < / b > < / td > < / tr > {{ for amount in right_side_amounts}} < tr > < td align = "right" > < b > {{player.left_side_amount}} < / b > now < td align = "middle" > < input type = "radio" value = "left" name = "{{ amount }}" required > & nbsp; & nbsp; < input type = "radio" name = "{{ amount }}" value = "right" data - amount = "{{ amount }}" required > < / td > < td align = "left" > < b > {{amount}} < / b > next month < / tr > {{endfor}} < / table > < button type = "button" class ="btn btn-primary" onclick="submitForm()" > Next < / button > {{endblock}} {{block scripts}} < script > let allRadios = document.querySelectorAll('input[type=radio]') function submitForm() { let form = document.getElementById('form'); if (form.reportValidity()) { let switchingPoint = document.getElementById('id_switching_point'); let allChoicesAreOnLeft = true; for (let radio of allRadios) { if (radio.value === 'right' & & radio.checked) { switchingPoint.value = radio.dataset.amount; allChoicesAreOnLeft = false; break; } } if (allChoicesAreOnLeft) { // '9999' represents the valueInput if the user didn't click the right side for any choice // it means their switching point is off the scale.you can change 9999 to some other valueInput // that is larger than any right-hand-side choice. switchingPoint.value = '9999'; } form.submit(); } } function onRadioClick(evt) { let clickedRadio = evt.target; let afterClickedRadio = false; let clickedRightRadio = clickedRadio.value == = 'right'; for (let aRadio of allRadios) { if (aRadio == = clickedRadio) { afterClickedRadio = true; continue; } if (clickedRightRadio & & afterClickedRadio & & aRadio.value === 'right') { aRadio.checked = true; } if (!clickedRightRadio & & !afterClickedRadio & & aRadio.value == = 'left') { aRadio.checked = true; } } } document.addEventListener("DOMContentLoaded", function(event) { for (let radio of document.querySelectorAll('input[type=radio]')) { radio.onchange = onRadioClick; } }); < / script > {{endblock}} rank_topN / __init__.py From otree - snippets from otree.api import * doc = """ Ranking your top N choices from a list of options. """ class C(BaseConstants): NAME_IN_URL = 'rank_topN' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 CHOICES = ['Martini', 'Margarita', 'White Russian', 'Pina Colada', 'Gin & Tonic'] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass def make_rank_field(label): return models.StringField(choices=C.CHOICES, label=label) class Player(BasePlayer): rank1 = make_rank_field("Top choice") rank2 = make_rank_field("Second choice") rank3 = make_rank_field("Third choice") class MyPage(Page): form_model = 'player' form_fields = ['rank1', 'rank2', 'rank3'] @staticmethod def error_message(player: Player, values): choices = [values['rank1'], values['rank2'], values['rank3']] # set() gives you distinct elements. if a list's length is different from its # set length, that means it must have duplicates. if len(set(choices)) != len(choices): return "You cannot choose the same item twice" class Results(Page): pass page_sequence = [MyPage, Results] rank_topN / Results.html From otree - snippets {{block content}} < p > Your top choices are {{player.rank1}}, {{player.rank2}}, and {{player.rank3}}. < / p > {{endblock}} rank_topN / MyPage.html From otree - snippets {{block title}} Rank your favorite drinks {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} gbat_treatments_complex / __init__.py From otree - snippets from otree.api import * doc = """ Similar to the basic gbat_treatments app, except: - Treatments are balanced rather than independently randomized. - The game persists for multiple rounds """ class C(BaseConstants): NAME_IN_URL = 'gbat_treatments_complex' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 3 # boolean works when there are 2 TREATMENTS # if you have >2 TREATMENTS, change this to numbers or strings like # [1, 2, 3] or ['A', 'B', 'C'], etc. TREATMENTS = [True, False] class Subsession(BaseSubsession): num_groups_created = models.IntegerField(initial=0) class Group(BaseGroup): pass class Player(BasePlayer): pass class GBATWaitPage(WaitPage): group_by_arrival_time = True @staticmethod def is_displayed(player: Player): """only do GBAT in the first round. this way, players stay in the same group for all rounds.""" return player.round_number == 1 @staticmethod def after_all_players_arrive(group: Group): subsession = group.subsession # % is the modulus operator. # so when num_groups_created exceeds the max list index, # we go back to 0, thus creating a cycle. idx = subsession.num_groups_created % len(C.TREATMENTS) treatment = C.TREATMENTS[idx] for p in group.get_players(): # since we want the treatment to persist for all rounds, we need to assign it # in a participant field (which persists across rounds) # rather than a group field, which is specific to the round. p.participant.time_pressure = treatment subsession.num_groups_created += 1 class MyPage(Page): pass page_sequence = [GBATWaitPage, MyPage] gbat_treatments_complex / MyPage.html From otree - snippets {{block title}} Round {{subsession.round_number}} {{endblock}} {{block content}} < p > Your group is assigned to the {{ if participant.time_pressure}} "time-pressure" {{ else}} "non-time-pressure" {{endif}} treatment. < / p > {{next_button}} {{endblock}} random_num_rounds_multiplayer_end / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'random_num_rounds_multiplayer_end' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # PAGES class MyPage(Page): pass page_sequence = [MyPage] random_num_rounds_multiplayer_end / Results.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} {{next_button}} {{endblock}} random_num_rounds_multiplayer_end / MyPage.html From otree - snippets {{block content}} Thank you. {{endblock}} slider_graphic / __init__.py From otree - snippets from otree.api import * doc = """ An image that changes when you move a slider. If your image is a some kind of chart, it's better to use Highcharts than static images. See the SVO example. """ class C(BaseConstants): NAME_IN_URL = 'slider_graphic' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): feeling = models.IntegerField(min=0, max=3) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['feeling'] @staticmethod def vars_for_template(player: Player): img_paths = ['slider_graphic/{}.svg'.format(i) for i in range(4)] return dict(img_paths=img_paths) page_sequence = [MyPage] slider_graphic / MyPage.html From otree - snippets {{block content}} < style > .slider - graphic { display: none; width: 6 em; } < / style > < p > Drag the slider to indicate how you feel right now. < / p > < input type = "range" name = "feeling" value = "1" min = "0" max = "3" oninput = "changeGraphic(this)" > {{ for img_path in img_paths}} < img src = "{{ static img_path }}" class ="slider-graphic" > {{endfor}} < script > let graphics = document.getElementsByClassName('slider-graphic'); function changeGraphic(input) { for (let img of graphics) { img.style.display = 'none'; } graphics[parseInt(input.value)].style.display = 'block'; } < / script > {{next_button}} {{endblock}} input_calculation / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'input_calculation' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 APR = 0.07 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): amount = models.CurrencyField(min=0, max=100000) num_years = models.IntegerField(min=1, max=50) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['amount', 'num_years'] @staticmethod def js_vars(player: Player): return dict(APR=C.APR) page_sequence = [MyPage] input_calculation / Results.html From otree - snippets {{block content}} < p > Thank you... < / p > {{endblock}} input_calculation / MyPage.html From otree - snippets {{block content}} < p > Choose what investment to make at an APR of {{C.APR}} < / p > {{formfields}} < br > < p > Your investment will be worth: < / p > < h2 > < span id = "projection" > < / span > < small > points < / small > < / h2 > {{next_button}} < script > let amountInput = document.getElementsByName('amount')[0]; let numYearsInput = document.getElementsByName('num_years')[0]; let projectionEle = document.getElementById('projection'); function recalc() { let amount = parseFloat(amountInput.value); let numYears = parseInt(numYearsInput.value); // isNaN is the javascript function that checks whether the value is a valid // number.need to check this because the field might be empty or // the user might have typed something other than a number. if (isNaN(amount) | | isNaN(numYears)) { projectionEle.innerText = ''; } else { let projection = amount * Math.pow((1 + js_vars.APR), numYears); projectionEle.innerText = Math.round(projection); } } amountInput.oninput = recalc; numYearsInput.oninput = recalc; < / script > {{endblock}} radio / __init__.py From otree - snippets from otree.api import * doc = """ Radio buttons in various layouts, looping over radio choices """ class C(BaseConstants): NAME_IN_URL = 'radio' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): f1 = models.IntegerField( widget=widgets.RadioSelect, choices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ) f2 = models.IntegerField( widget=widgets.RadioSelect, choices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ) # PAGES class MyPage(Page): form_model = 'player' form_fields = ['f1', 'f2'] page_sequence = [MyPage] radio / MyPage.html From otree - snippets {{block content}} < p > < i > Radio buttons without labels(visual / analog scale, similar to a slider) < / i > < / p > < p > Least & nbsp; {{ for choice in form.f1}} {{choice}} {{endfor}} & nbsp; Most < / p > {{formfield_errors 'f1'}} < br > < p > < i > Labels under radio buttons < / i > < / p > < div style = "display: flex" > {{ for choice in form.f2}} < div style = "flex: 1; text-align: center" > {{choice}} < br > < span style = "text-align: center" > {{choice.label}} < / span > < / div > {{endfor}} < / div > {{formfield_errors 'f2'}} < br > { # todo: radio buttons laid out individually, no loop (by index) #} {{next_button}} {{endblock}} appcopy1 / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'appcopy1' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): bbb = models.IntegerField(widget=widgets.RadioSelectHorizontal) def bbb_choices(player: Player): return [1, 2, 3] class MyPage(Page): # every page needs an explicit template_name template_name = 'appcopy1/MyPage.html' form_model = 'player' form_fields = ['bbb'] page_sequence = [MyPage] appcopy1 / MyPage.html From otree - snippets {{block title}} App A {{endblock}} {{block content}} < p > < i > This app gets repeated, with another app in between.< / i > < / p > {{formfields}} {{next_button}} {{endblock}} pay_random_app3 / PayRandomApp.html From otree - snippets {{block content}} < p > A random app will now be chosen for payment.< / p > {{next_button}} {{endblock}} pay_random_app3 / __init__.py From otree - snippets from otree.api import * doc = """ App where we choose the app to be paid """ class C(BaseConstants): NAME_IN_URL = 'pay_random_app3' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): app_to_pay = models.StringField() class PayRandomApp(Page): @staticmethod def before_next_page(player: Player, timeout_happened): import random participant = player.participant # print('participant.app_payoffs is', participant.app_payoffs) apps = [ 'pay_random_app1', 'pay_random_app2', ] app_to_pay = random.choice(apps) participant.payoff = participant.app_payoffs[app_to_pay] player.app_to_pay = app_to_pay class Results(Page): pass page_sequence = [PayRandomApp, Results] pay_random_app3 / Results.html From otree - snippets {{block title}} Final Results {{endblock}} {{block content}} < p > The app that was randomly chosen for payment is {{player.app_to_pay}}. You payoff from that app (and therefore your total payoff) is {{participant.payoff}}. < / p > {{endblock}} min_time_on_page / Page1.html From otree - snippets {{block title}} Page 1 {{endblock}} {{block content}} < p > < i > Click next... < / i > < / p > {{next_button}} {{endblock}} min_time_on_page / Page2.html From otree - snippets {{block title}} Page 2 {{endblock}} {{block content}} < p > You must stay on this page for at least 10 seconds.< / p > {{next_button}} {{endblock}} min_time_on_page / Page3.html From otree - snippets {{block title}} Page 3 {{endblock}} {{block content}} {{endblock}} min_time_on_page / __init__.py From otree - snippets from otree.api import * doc = """ Minimum time on a page """ class C(BaseConstants): NAME_IN_URL = 'min_time_on_page' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): page_pass_time = models.FloatField() class Page1(Page): @staticmethod def before_next_page(player: Player, timeout_happened): import time player.page_pass_time = time.time() + 10 # PAGES class Page2(Page): @staticmethod def error_message(player: Player, values): import time if time.time() < player.page_pass_time: return "You cannot pass this page yet." class Page3(Page): pass page_sequence = [Page1, Page2, Page3] progress_bar / Page1.html From otree - snippets {{block content}} {{include_sibling 'progress.html'}} {{next_button}} {{endblock}} progress_bar / Page2.html From otree - snippets {{block content}} {{include_sibling 'progress.html'}} {{next_button}} {{endblock}} progress_bar / __init__.py From otree - snippets from otree.api import * doc = """ All you need is a participant field called 'progress' then keep adding 1 to it. """ class C(BaseConstants): NAME_IN_URL = 'progress_bar' PLAYERS_PER_GROUP = None NUM_ROUNDS = 5 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): for player in subsession.get_players(): participant = player.participant participant.progress = 1 class Group(BaseGroup): pass class Player(BasePlayer): pass class Page1(Page): @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant # remember to add 'progress' to PARTICIPANT_FIELDS. participant.progress += 1 class Page2(Page): @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant # progress can be defined in different ways, not only by page number # (especially if pages get skipped) # so feel free to do things like: # - incrementing by more than 1: # participant.progress += 2 # - setting to a specific valueInput: # participant.progress = 8 participant.progress += 1 page_sequence = [Page1, Page2] progress_bar / progress.html From otree - snippets < !-- Simplest way to calculate the "max" is to run through the experiment once and then see what participant.progress is at the very end, then plug that in here. if you want a prettier progress bar, you can use Bootstrap's. --> < p > < label > Step {{participant.progress}} of 10 < progress value = "{{ participant.progress }}" max = "10" > < / progress > < / label > < / p > random_task_order / TaskA.html From otree - snippets {{block title}} Task A {{endblock}} {{block content}} {{next_button}} {{endblock}} random_task_order / TaskC.html From otree - snippets {{block title}} Task C {{endblock}} {{block content}} {{next_button}} {{endblock}} random_task_order / __init__.py From otree - snippets import random from otree.api import * doc = """ For each participant, randomize the order of tasks A, B, and C. Task B has 2 pages, which are always shown in the same order. The page_sequence contains all tasks; in each round we show a randomly determined subset of pages. """ class C(BaseConstants): NAME_IN_URL = 'random_task_order' PLAYERS_PER_GROUP = None TASKS = ['A', 'B', 'C'] NUM_ROUNDS = len(TASKS) class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # FUNCTIONS def creating_session(subsession: Subsession): if subsession.round_number == 1: for p in subsession.get_players(): round_numbers = list(range(1, C.NUM_ROUNDS + 1)) random.shuffle(round_numbers) task_rounds = dict(zip(C.TASKS, round_numbers)) # print('player', p.id_in_subsession) # print('task_rounds is', task_rounds) p.participant.task_rounds = task_rounds # PAGES class TaskA(Page): @staticmethod def is_displayed(player: Player): participant = player.participant return player.round_number == participant.task_rounds['A'] class TaskB1(Page): @staticmethod def is_displayed(player: Player): participant = player.participant return player.round_number == participant.task_rounds['B'] class TaskB2(Page): @staticmethod def is_displayed(player: Player): participant = player.participant return player.round_number == participant.task_rounds['B'] class TaskC(Page): @staticmethod def is_displayed(player: Player): participant = player.participant return player.round_number == participant.task_rounds['C'] page_sequence = [ TaskA, TaskB1, TaskB2, TaskC, ] random_task_order / TaskB1.html From otree - snippets {{block title}} Task B, Page 1 {{endblock}} {{block content}} {{next_button}} {{endblock}} random_task_order / TaskB2.html From otree - snippets {{block title}} Task B, Page 2 {{endblock}} {{block content}} {{next_button}} {{endblock}} treatments_from_spreadsheet / __init__.py From otree - snippets from otree.api import * doc = """ Reading treatment parameters from a CSV spreadsheet """ class C(BaseConstants): NAME_IN_URL = 'treatments_from_spreadsheet' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): import csv f = open(__name__ + '/treatments.csv', encoding='utf-8-sig') rows = list(csv.DictReader(f)) players = subsession.get_players() for i in range(len(players)): row = rows[i] player = players[i] # CSV contains all data in string form, so we need to convert # to the correct data type, e.g. '1' -> 1 -> True. player.time_pressure = bool(int(row['time_pressure'])) player.high_tax = bool(int(row['high_tax'])) player.endowment = cu(row['endowment']) player.color = row['color'] class Group(BaseGroup): pass class Player(BasePlayer): time_pressure = models.BooleanField() endowment = models.CurrencyField() high_tax = models.BooleanField() color = models.StringField() class MyPage(Page): pass page_sequence = [MyPage] treatments_from_spreadsheet / MyPage.html From otree - snippets {{block content}} < p > < i > Look in the admin "data" tab to see the treatments that were assigned. < / i > < / p > {{endblock}} pass_data_between_apps_part1 / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'pass_data_between_apps1' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): language = models.StringField(label='What is your main language?') # PAGES class MyPage(Page): form_model = 'player' form_fields = ['language'] @staticmethod def before_next_page(player: Player, timeout_happened): participant = player.participant # in settings.py need to add 'language' to PARTICIPANT_FIELDS. participant.language = player.language page_sequence = [MyPage] pass_data_between_apps_part1 / MyPage.html From otree - snippets {{block title}} App 1 {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} gbat_keep_same_groups_part1 / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'gbat_keep_same_groups' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class GBATWait(WaitPage): group_by_arrival_time = True @staticmethod def after_all_players_arrive(group: Group): # save each participant's current group ID so it can be # accessed in the next app. for p in group.get_players(): participant = p.participant participant.past_group_id = group.id class MyPage(Page): pass page_sequence = [GBATWait, MyPage] gbat_keep_same_groups_part1 / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > < i > group_by_arrival_time has paired you with a partner. < / i > < / p > {{next_button}} {{endblock}} gbat_keep_same_groups_part2 / __init__.py From otree - snippets from otree.api import * doc = """ Preserve same groups as a previous app that used group_by_arrival time. """ class C(BaseConstants): NAME_IN_URL = 'gbat_keep_same_groups_part2' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def group_by_arrival_time_method(subsession: Subsession, waiting_players): # we now place users into different baskets, according to their group in the previous app. # the dict 'd' will contain all these baskets. d = {} for p in waiting_players: group_id = p.participant.past_group_id if group_id not in d: # since 'd' is initially empty, we need to initialize an empty list (basket) # each time we see a new group ID. d[group_id] = [] players_in_my_group = d[group_id] players_in_my_group.append(p) if len(players_in_my_group) == 2: return players_in_my_group # print('d is', d) class Group(BaseGroup): pass class Player(BasePlayer): pass class GBATWait(WaitPage): group_by_arrival_time = True class MyPage(Page): pass page_sequence = [GBATWait, MyPage] gbat_keep_same_groups_part2 / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > < i > This is the next app.Again you have been paired with the same partner.< / i > < / p > {{next_button}} {{endblock}} appcopy2 / __init__.py From otree - snippets from appcopy1 import * class C(C): NAME_IN_URL = 'appcopy2' # need to copy/paste Subsession/Group/Player classes from appcopy1 class Subsession(BaseSubsession): pass class Group(BaseGroup): aaa = models.IntegerField() class Player(BasePlayer): bbb = models.IntegerField() questions_from_csv_complex / __init__.py From otree - snippets from otree.api import * doc = """ Read quiz questions from a CSV (complex version). See also the 'simple' version. It would be much simpler to implement this using rounds (1 question per round), as is done in the 'simple' version; however, this approach has faster gameplay since it's all done in 1 page, and leads to a more compact data export. Consider using this version if you have many questions or if speed is a high priority. """ class C(BaseConstants): NAME_IN_URL = 'questions_from_csv_complex' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 def read_csv(): import csv import random f = open(__name__ + '/stimuli.csv', encoding='utf-8-sig') rows = list(csv.DictReader(f)) random.shuffle(rows) return rows class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): for p in subsession.get_players(): stimuli = read_csv() p.num_trials = len(stimuli) for stim in stimuli: # print('stim is', stim) # ** is the Python operator to unpack the dict Trial.create(player=p, **stim) class Group(BaseGroup): pass class Player(BasePlayer): num_correct = models.IntegerField(initial=0) raw_responses = models.LongStringField() class Trial(ExtraModel): player = models.Link(Player) question = models.StringField() optionA = models.StringField() optionB = models.StringField() optionC = models.StringField() solution = models.StringField() choice = models.StringField() is_correct = models.BooleanField() def to_dict(trial: Trial): return dict( question=trial.question, optionA=trial.optionA, optionB=trial.optionB, optionC=trial.optionC, id=trial.id, ) # PAGES class Stimuli(Page): form_model = 'player' form_fields = ['raw_responses'] @staticmethod def js_vars(player: Player): stimuli = [to_dict(trial) for trial in Trial.filter(player=player)] return dict(trials=stimuli) @staticmethod def before_next_page(player: Player, timeout_happened): import json responses = json.loads(player.raw_responses) for trial in Trial.filter(player=player): # have to use str() because Javascript implicitly converts keys to strings trial.choice = responses[str(trial.id)] trial.is_correct = trial.choice == trial.solution # convert True/False to 1/0 player.num_correct += int(trial.is_correct) # don't need it anymore player.raw_responses = '' class Results(Page): @staticmethod def vars_for_template(player: Player): return dict(trials=Trial.filter(player=player)) page_sequence = [Stimuli, Results] def custom_export(players): yield ['participant', 'question', 'choice', 'is_correct'] for player in players: participant = player.participant trials = Trial.filter(player=player) for t in trials: yield [participant.code, t.question, t.choice, t.is_correct] questions_from_csv_complex / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > You gave {{player.num_correct}} correct answers. < / p > < table class ="table" > < tr > < th > question < / th > < th > optionA < / th > < th > optionB < / th > < th > optionC < / th > < th > Your choice < / th > < th > solution < / th > < th > correct? < / th > < / tr > {{ for trial in trials}} < tr > < td > {{trial.question}} < / td > < td > {{trial.optionA}} < / td > < td > {{trial.optionB}} < / td > < td > {{trial.optionC}} < / td > < td > {{trial.choice}} < / td > < td > {{trial.solution}} < / td > < td > {{trial.is_correct}} < / td > < / tr > {{endfor}} < / table > {{endblock}} questions_from_csv_complex / Stimuli.html From otree - snippets {{block title}} {{endblock}} {{block content}} < p id = "question" > < / p > < div > < button type = "button" onclick = "recordResponse(this)" value = "A" id = "optionA" > < / button > < button type = "button" onclick = "recordResponse(this)" value = "B" id = "optionB" > < / button > < button type = "button" onclick = "recordResponse(this)" value = "C" id = "optionC" > < / button > < / div > < input type = "hidden" name = "raw_responses" id = "raw_responses" > < script > let responses = {} let trialIndex = 0; let trials = js_vars.trials; function updateUI() { for (let item of['question', 'optionA', 'optionB', 'optionC']) { document.getElementById(item).innerText = trials[trialIndex][item]; } } function recordResponse(btn) { let trialId = trials[trialIndex].id; responses[trialId] = btn.value; trialIndex + +; if (trialIndex === trials.length) { document.getElementById('raw_responses').value = JSON.stringify(responses) document.getElementById('form').submit(); } else { updateUI(); } } updateUI(); < / script > {{endblock}} multi_select_complex / __init__.py From otree - snippets from otree.api import * doc = """ Question that lets you select multiple options (multi-select, multiple choice / multiple answer) The difference is that this one lets you customize the label of each checkbox, and requires at least 1 to be selected. """ class C(BaseConstants): NAME_IN_URL = 'multi_select_complex' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 LANGUAGES = [ dict(name='english', label="I speak English"), dict(name='french', label="Je parle français"), dict(name='spanish', label="Hablo español"), dict(name='finnish', label="Puhun suomea"), ] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): english = models.BooleanField(blank=True) french = models.BooleanField(blank=True) spanish = models.BooleanField(blank=True) finnish = models.BooleanField(blank=True) # PAGES class MyPage(Page): form_model = 'player' @staticmethod def get_form_fields(player: Player): return [lang['name'] for lang in C.LANGUAGES] @staticmethod def error_message(player: Player, values): # print('values is', values) num_selected = 0 for lang in C.LANGUAGES: if values[lang['name']]: num_selected += 1 if num_selected < 1: return "You must select at least 1 language." page_sequence = [MyPage] multi_select_complex / MyPage.html From otree - snippets {{block content}} < p > What languages do you speak? Select all that apply. < / p > {{ for field in C.LANGUAGES}} < label > < input type = "checkbox" name = "{{ field.name }}" value = "1" > {{field.label}} < / label > < br > {{endfor}} < p > {{next_button}} < / p > {{endblock}} factorial_treatments / __init__.py From otree - snippets from otree.api import * doc = """Randomize multiple factors in a balanced way""" class C(BaseConstants): NAME_IN_URL = 'randomize_cross_product' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession): import itertools treatments = itertools.cycle( itertools.product([True, False], [True, False], [100, 200, 300]) ) for p in subsession.get_players(): treatment = next(treatments) # print('treatment is', treatment) p.time_pressure = treatment[0] p.high_tax = treatment[1] p.endowment = treatment[2] class Group(BaseGroup): pass class Player(BasePlayer): time_pressure = models.BooleanField() high_tax = models.BooleanField() endowment = models.CurrencyField() class MyPage(Page): pass page_sequence = [MyPage] factorial_treatments / MyPage.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > < i > Check the admin 'Data' tab to see the results of the randomization < / i > < / p > {{endblock}} random_question_order / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'random_question_order' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): aaa = models.BooleanField() bbb = models.BooleanField() ccc = models.StringField() ddd = models.IntegerField() # PAGES class MyPage(Page): form_model = 'player' @staticmethod def get_form_fields(player: Player): import random form_fields = ['aaa', 'bbb', 'ccc', 'ddd'] random.shuffle(form_fields) return form_fields page_sequence = [MyPage] random_question_order / MyPage.html From otree - snippets {{block title}} Answer these questions {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} bmi_calculator / __init__.py From otree - snippets from otree.api import * doc = """ Basic single-player game (BMI calculator) """ class C(BaseConstants): NAME_IN_URL = 'bmi_calculator' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): weight_kg = models.IntegerField(label="Weight (in kg)") height_cm = models.IntegerField(label="Height (in cm)") bmi = models.FloatField() # PAGES class MyPage(Page): form_model = 'player' form_fields = ['weight_kg', 'height_cm'] @staticmethod def before_next_page(player: Player, timeout_happened): bmi = player.weight_kg / ((player.height_cm / 100) ** 2) player.bmi = round(bmi, 1) class Results(Page): pass page_sequence = [MyPage, Results] bmi_calculator / Results.html From otree - snippets {{block content}} < p > Your BMI is {{player.bmi}}. < / p > {{endblock}} bmi_calculator / MyPage.html From otree - snippets {{block title}} BMI(Body Mass Index) calculator {{endblock}} {{block content}} {{formfields}} {{next_button}} {{endblock}} wait_for_specific_people / WaitForSelected.html From otree - snippets {{block title}} Waiting {{endblock}} {{block content}} < progress > < / progress > < p > Waiting for players: < span id = "wait_for_ids" > < / span > < / p > < script > function liveRecv(data) { console.log('data', data) if (data.finished) { document.getElementById("form").submit(); } else { document.getElementById('wait_for_ids').innerText = data.not_arrived_yet; } } document.addEventListener("DOMContentLoaded", (event) = > { liveSend({}); }); < / script > {{endblock}} wait_for_specific_people / __init__.py From otree - snippets from otree.api import * doc = """ Wait only for specific people """ class C(BaseConstants): NAME_IN_URL = 'wait_for_specific_people' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): session = subsession.session import random session.wait_for_ids = set() session.arrived_ids = set() for p in subsession.get_players(): # we just determine it randomly here. # in your game, you should replace it with your desired logic. selected = random.choice([False, True]) p.selected_for_waitpage = selected if selected: session.wait_for_ids.add(p.id_in_subsession) class Group(BaseGroup): pass class Player(BasePlayer): selected_for_waitpage = models.BooleanField() class Intro(Page): pass class WaitForSelected(Page): @staticmethod def is_displayed(player: Player): return player.selected_for_waitpage @staticmethod def live_method(player: Player, data): session = player.session session.arrived_ids.add(player.id_in_subsession) not_arrived_yet = session.wait_for_ids - session.arrived_ids if not_arrived_yet: return {0: dict(not_arrived_yet=list(not_arrived_yet))} return {0: dict(finished=True)} @staticmethod def error_message(player: Player, values): session = player.session if session.arrived_ids != session.wait_for_ids: return "Page somehow proceeded before all players are ready" class Results(Page): pass page_sequence = [Intro, WaitForSelected, Results] wait_for_specific_people / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > < i > Next page content would go here... < / i > < / p > {{next_button}} {{endblock}} wait_for_specific_people / Intro.html From otree - snippets {{block title}} Intro {{endblock}} {{block content}} < p > This app demonstrates how to have a waiting page that just waits for certain people to arrive before proceeding. You can make it any subset of participants: for example, just the participants you marked as being online currently, or just those who gave a specific answer to a question. < / p > < p > In this demo, the players were randomly selected as: {{session.wait_for_ids}}. < / p > < p > You are player {{player.id_in_subsession}}, so you {{ if player.selected_for_waitpage}} must wait on {{ else}} can skip {{endif}} the following wait page. < / p > < p > Click next. < / p > {{next_button}} {{endblock}} practice_rounds / __init__.py From otree - snippets from otree.api import * doc = """Practice rounds""" class C(BaseConstants): NAME_IN_URL = 'practice_rounds' PLAYERS_PER_GROUP = None NUM_PRACTICE_ROUNDS = 2 NUM_REAL_ROUNDS = 10 NUM_ROUNDS = NUM_PRACTICE_ROUNDS + NUM_REAL_ROUNDS class Subsession(BaseSubsession): is_practice_round = models.BooleanField() real_round_number = models.IntegerField() def creating_session(subsession: Subsession): # In Python, 'a <= b' produces either True or False. subsession.is_practice_round = ( subsession.round_number <= C.NUM_PRACTICE_ROUNDS ) if not subsession.is_practice_round: subsession.real_round_number = ( subsession.round_number - C.NUM_PRACTICE_ROUNDS ) class Group(BaseGroup): pass class Player(BasePlayer): response = models.IntegerField() solution = models.IntegerField() is_correct = models.BooleanField() class Play(Page): form_model = 'player' form_fields = ['response'] @staticmethod def before_next_page(player: Player, timeout_happened): # the **2 is just an example used in this game (squaring a number) player.solution = player.round_number ** 2 player.is_correct = player.response == player.solution class PracticeFeedback(Page): @staticmethod def is_displayed(player: Player): subsession = player.subsession return subsession.is_practice_round class Results(Page): @staticmethod def is_displayed(player: Player): return player.round_number == C.NUM_ROUNDS @staticmethod def vars_for_template(player: Player): score = 0 for p in player.in_rounds( C.NUM_PRACTICE_ROUNDS + 1, C.NUM_ROUNDS ): score += p.is_correct return dict(score=score) page_sequence = [Play, PracticeFeedback, Results] practice_rounds / Results.html From otree - snippets {{block title}} Results {{endblock}} {{block content}} < p > Your got {{score}} answers correct. < / p > {{endblock}} practice_rounds / PracticeFeedback.html From otree - snippets {{block title}} Practice feedback {{endblock}} {{block content}} {{ if player.is_correct}} < p > You got the practice question correct! < / p > {{ else}} < p > You answered {{player.response}} but the correct answer was {{player.solution}}. < / p > {{endif}} < p > Once the real rounds start, you won 't see this feedback page anymore.
{{next_button}} {{endblock}} practice_rounds / Play.html From otree - snippets {{block title}} {{ if subsession.is_practice_round}} Practice round {{subsession.round_number}} of {{C.NUM_PRACTICE_ROUNDS}} {{ else}} Round {{subsession.real_round_number}} of {{C.NUM_REAL_ROUNDS}} {{endif}} {{endblock}} {{block content}} < p > Math question: what is {{player.round_number}} squared? < / p > {{formfields}} {{next_button}} {{endblock}} pay_random_app_multi_player / __init__.py From otree - snippets from otree.api import * doc = """ Your app description """ class C(BaseConstants): NAME_IN_URL = 'pay_random_app1' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass def creating_session(subsession: Subsession): for p in subsession.get_players(): # initialize an empty dict to store how much they made in each app p.participant.app_payoffs = {} class Group(BaseGroup): pass class Player(BasePlayer): potential_payoff = models.CurrencyField() # PAGES class MyPage(Page): pass class ResultsWaitPage(WaitPage): @staticmethod def after_all_players_arrive(group: Group): """ In multiplayer games, payoffs are typically set in after_all_players_arrive, so that's what we demonstrate here. """ import random for p in group.get_players(): participant = p.participant potential_payoff = random.randint(100, 200) p.potential_payoff = potential_payoff # __name__ is a magic variable that contains the name of the current app participant.app_payoffs[__name__] = potential_payoff class Results(Page): pass page_sequence = [MyPage, ResultsWaitPage, Results] pay_random_app_multi_player / Results.html From otree - snippets {{block title}} App 1 Results {{endblock}} {{block content}} < p > Your payoff in this app is {{player.potential_payoff}}. < / p > {{next_button}} {{endblock}} pay_random_app_multi_player / MyPage.html From otree - snippets {{block title}} App 1 {{endblock}} {{block content}} < p > < i > Your game would normally go here.In this case, your payoff will be determined randomly. < / i > < / p > {{next_button}} {{endblock}} supergames / NewSupergame.html From otree - snippets {{block title}} Supergame {{subsession.sg}} {{endblock}} {{block content}} < p > This page is only shown at the beginning of a supergame... < / p > {{next_button}} {{endblock}} chat_with_experimenter / papercups.html From otree - snippets < script > window.Papercups = { config: { accountId: "5ee2437e-b9e9-4348-8e1c-483959b1d826", title: "Welcome to our experiment", subtitle: "Ask us anything in the chat window below", primaryColor: "#1890ff", greeting: "", awayMessage: "", newMessagePlaceholder: "Start typing...", showAgentAvailability: false, agentAvailableText: "We're online right now!", agentUnavailableText: "We're away at the moment.", requireEmailUpfront: false, iconVariant: "outlined", // note: you need to set up your own Papercups chat server(quite easy). baseUrl: "https://otree-papercups.herokuapp.com", customer: { name: '{{participant.code}}', external_id: '{{participant.code}}', } }, }; < / script > < script type = "text/javascript" async defer src = "https://otree-papercups.herokuapp.com/widget.js" > < / script > gbat_treatments / MyPage.html From otree - snippets {{block content}} Your group is in the {{ if group.treatment}} treatment {{ else}} control {{endif}} cohort. {{endblock}} supergames / __init__.py From otree - snippets from otree.api import * doc = """ Supergames consisting of multiple rounds each """ def cumsum(lst): total = 0 new = [] for ele in lst: total += ele new.append(total) return new class C(BaseConstants): NAME_IN_URL = 'supergames' PLAYERS_PER_GROUP = None # first supergame lasts 2 rounds, second supergame lasts 3 rounds, etc... ROUNDS_PER_SG = [2, 3, 4, 5] SG_ENDS = cumsum(ROUNDS_PER_SG) # print('SG_ENDS is', SG_ENDS) NUM_ROUNDS = sum(ROUNDS_PER_SG) class Subsession(BaseSubsession): sg = models.IntegerField() period = models.IntegerField() is_last_period = models.BooleanField() def creating_session(subsession: Subsession): if subsession.round_number == 1: sg = 1 period = 1 # loop over all subsessions for ss in subsession.in_rounds(1, C.NUM_ROUNDS): ss.sg = sg ss.period = period # 'in' gives you a bool. for example: 5 in [1, 5, 6] # => True is_last_period = ss.round_number in C.SG_ENDS ss.is_last_period = is_last_period if is_last_period: sg += 1 period = 1 else: period += 1 class Group(BaseGroup): pass class Player(BasePlayer): pass class NewSupergame(Page): @staticmethod def is_displayed(player: Player): subsession = player.subsession return subsession.period == 1 class Play(Page): pass page_sequence = [NewSupergame, Play] supergames / Play.html From otree - snippets {{block title}} Supergame {{subsession.sg}}, period {{subsession.period}} {{endblock}} {{block content}} < p > < i > Your game goes here... < / i > < / p > {{next_button}} {{endblock}} show_other_players_payoffs / __init__.py From otree - snippets from otree.api import * class C(BaseConstants): NAME_IN_URL = 'show_other_players_payoffs' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass class Results(Page): @staticmethod def vars_for_template(player: Player): return dict(others=player.get_others_in_group()) page_sequence = [Results] show_other_players_payoffs / Results.html From otree - snippets {{block title}} Page title {{endblock}} {{block content}} < p > Your payoff is {{player.payoff}}. < / p > < p > Here are the other players ' payoffs: < table > {{ for other in others}} < tr > < td > Player {{other.id_in_group}} < / td > < td > {{other.payoff}} < / td > < / tr > {{endfor}} < / table > {{endblock}} getattr_setattr / Page1.html From otree - snippets {{block content}} < p > Enter 10 random numbers from 1 to 100. < / p > {{formfields}} {{next_button}} {{endblock}} getattr_setattr / Page2.html From otree - snippets {{block content}} {{formfields}} {{next_button}} {{endblock}} getattr_setattr / __init__.py From otree - snippets from otree.api import * doc = """ Using getattr() and setattr() to access numbered fields, e.g. player.num1, player.num2, ..., player.num10, without writing repetitive if-statements. NOTE: having numbered fields is often not the best or easiest design. For example, let's say you have fields like this: num1 = models.IntegerField() num2 = models.IntegerField() ... num10 = models.IntegerField() If you don't need to put them in a form, then you can replace this simply with a list in a participant field, since they can be more easily accessed by number, e.g. participant.my_numbers[5] If you have many numbered fields, like more than 20, you should consider using ExtraModel. Participant fields and ExtraModel also have the advantage that you don't need to know in advance exactly how many you will have. """ class C(BaseConstants): NAME_IN_URL = 'getattr_setattr' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): num1 = models.IntegerField() num2 = models.IntegerField() num3 = models.IntegerField() num4 = models.IntegerField() num5 = models.IntegerField() num6 = models.IntegerField() num7 = models.IntegerField() num8 = models.IntegerField() num9 = models.IntegerField() num10 = models.IntegerField() chosen_number = models.IntegerField( choices=C.NUMBERS, label="Choose a random number from 1 to 10" ) class Page1(Page): form_model = 'player' form_fields = ['num{}'.format(n) for n in C.NUMBERS] class Page2(Page): form_model = 'player' form_fields = ['chosen_number'] class Results(Page): @staticmethod def vars_for_template(player: Player): # if chosen_number was 7, this will give you player.num7 field_name = 'num{}'.format(player.chosen_number) chosen_value = getattr(player, field_name) player.payoff = chosen_value # if chosen number was 7, this gives you # player.num1 + player.num2 + ... + player.num7 sum_to_n = sum( getattr(player, 'num{}'.format(n)) for n in range(1, player.chosen_number + 1) ) return dict(chosen_value=chosen_value, sum_to_n=sum_to_n) page_sequence = [Page1, Page2, Results] getattr_setattr / Results.html From otree - snippets {{block content}} < p > You chose number {{player.chosen_number}}. The random number in that field was {{chosen_value}}. Therefore, your payoff is {{player.payoff}}. By the way, the sum of all numbers from num1 to num {{player.chosen_number}} was {{sum_to_n}}. < / p > {{endblock}} survey / CognitiveReflectionTest.html From otree - demo {{block title}}Survey {{endblock}} {{block content}} < p > Please answer the following questions. < / p > {{formfields}} {{next_button}} {{endblock}} matching_pennies / Choice.html From otree - demo {{block title}}Round {{subsession.round_number}} of {{C.NUM_ROUNDS}} {{endblock}} {{block content}} < h4 > Instructions < / h4 > < p > This is a matching pennies game. Player 1 is the 'Mismatcher' and wins if the choices mismatch; Player 2 is the 'Matcher' and wins if they match. < / p > < p > At the end, a random round will be chosen for payment. < / p > < p > < h4 > Round history < / h4 > < table class ="table" > < tr > < th > Round < / th > < th > Player and outcome < / th > < / tr > {{ for p in player_in_previous_rounds}} < tr > < td > {{p.round_number}} < / td > < td > You were the {{p.role}} and {{ if p.is_winner}} won {{ else}} lost {{endif}} < / td > < / tr > {{endfor}} < / table > < p > In this round, you are the {{player.role}}. < / p > {{formfields}} {{next_button}} {{endblock}} matching_pennies / __init__.py From otree - demo from otree.api import * doc = """ A demo of how rounds work in oTree, in the context of 'matching pennies' """ class C(BaseConstants): NAME_IN_URL = 'matching_pennies' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 4 STAKES = cu(100) MATCHER_ROLE = 'Matcher' MISMATCHER_ROLE = 'Mismatcher' class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): penny_side = models.StringField( choices=[['Heads', 'Heads'], ['Tails', 'Tails']], widget=widgets.RadioSelect, label="I choose:", ) is_winner = models.BooleanField() # FUNCTIONS def creating_session(subsession: Subsession): session = subsession.session import random if subsession.round_number == 1: paying_round = random.randint(1, C.NUM_ROUNDS) session.vars['paying_round'] = paying_round if subsession.round_number == 3: # reverse the roles matrix = subsession.get_group_matrix() for row in matrix: row.reverse() subsession.set_group_matrix(matrix) if subsession.round_number > 3: subsession.group_like_round(3) def set_payoffs(group: Group): subsession = group.subsession session = group.session p1 = group.get_player_by_id(1) p2 = group.get_player_by_id(2) for p in [p1, p2]: is_matcher = p.role == C.MATCHER_ROLE p.is_winner = (p1.penny_side == p2.penny_side) == is_matcher if subsession.round_number == session.vars['paying_round'] and p.is_winner: p.payoff = C.STAKES else: p.payoff = cu(0) # PAGES class Choice(Page): form_model = 'player' form_fields = ['penny_side'] @staticmethod def vars_for_template(player: Player): return dict(player_in_previous_rounds=player.in_previous_rounds()) class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class ResultsSummary(Page): @staticmethod def is_displayed(player: Player): return player.round_number == C.NUM_ROUNDS @staticmethod def vars_for_template(player: Player): session = player.session player_in_all_rounds = player.in_all_rounds() return dict( total_payoff=sum([p.payoff for p in player_in_all_rounds]), paying_round=session.vars['paying_round'], player_in_all_rounds=player_in_all_rounds, ) page_sequence = [Choice, ResultsWaitPage, ResultsSummary] dictator / __init__.py From otree - demo from otree.api import * doc = """ One player decides how to divide a certain amount between himself and the other player. See: Kahneman, Daniel, Jack L. Knetsch, and Richard H. Thaler. "Fairness and the assumptions of economics." Journal of business (1986): S285-S300. """ class C(BaseConstants): NAME_IN_URL = 'dictator' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 # Initial amount allocated to the dictator ENDOWMENT = cu(100) class Subsession(BaseSubsession): pass class Group(BaseGroup): kept = models.CurrencyField( doc="""Amount dictator decided to keep for himself""", min=0, max=C.ENDOWMENT, label="I will keep", ) class Player(BasePlayer): pass # FUNCTIONS def set_payoffs(group: Group): p1 = group.get_player_by_id(1) p2 = group.get_player_by_id(2) p1.payoff = group.kept p2.payoff = C.ENDOWMENT - group.kept # PAGES class Introduction(Page): pass class Offer(Page): form_model = 'group' form_fields = ['kept'] @staticmethod def is_displayed(player: Player): return player.id_in_group == 1 class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): @staticmethod def vars_for_template(player: Player): group = player.group return dict(offer=C.ENDOWMENT - group.kept) page_sequence = [Introduction, Offer, ResultsWaitPage, Results] dictator / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < p > {{ if player.id_in_group == 1}} You decided to keep < strong > {{group.kept}} < / strong > for yourself. {{ else}} Participant 1 decided to keep < strong > {{group.kept}} < / strong >, so you got < strong > {{offer}} < / strong >. {{endif}} {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} dictator / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > You will be paired randomly and anonymously with another participant. In this study, one of you will be Participant 1 and the other Participant 2. Prior to making a decision, you will learn your role, which will be randomly assigned. < / p > < p > There is {{C.ENDOWMENT}} to split.Participant 1 will decide how much she or he will retain.Then the rest will go to Participant 2. < / p > < / div > < / div > dictator / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} dictator / Offer.html From otree - demo {{block title}}Your Decision {{endblock}} {{block content}} < p > You are < strong > Participant 1 < / strong >. Please decide how much of the {{C.ENDOWMENT}} you will keep for yourself. < / p > {{formfields}} {{next_button}} {{include_sibling 'instructions.html'}} {{endblock}} trust / SendBack.html From otree - demo {{block title}}Your Choice {{endblock}} {{block content}} < p > You are Participant B. Participant A sent you {{group.sent_amount}} and you received {{tripled_amount}}. Now you have {{tripled_amount}}. How much will you send to participant A? < / p > {{formfields}} < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} trust / Send.html From otree - demo {{block title}}Your Choice {{endblock}} {{block content}} < p > You are Participant A.Now you have {{C.ENDOWMENT}}.How much will you send to participant B? < / p > {{formfields}} < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} trust / __init__.py From otree - demo from otree.api import * doc = """ This is a standard 2-player trust game where the amount sent by player 1 gets tripled. The trust game was first proposed by Berg, Dickhaut, and McCabe (1995) . """ class C(BaseConstants): NAME_IN_URL = 'trust' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 # Initial amount allocated to each player ENDOWMENT = cu(100) MULTIPLIER = 3 class Subsession(BaseSubsession): pass class Group(BaseGroup): sent_amount = models.CurrencyField( min=0, max=C.ENDOWMENT, doc="""Amount sent by P1""", label="Please enter an amount from 0 to 100:", ) sent_back_amount = models.CurrencyField(doc="""Amount sent back by P2""", min=cu(0)) class Player(BasePlayer): pass # FUNCTIONS def sent_back_amount_max(group: Group): return group.sent_amount * C.MULTIPLIER def set_payoffs(group: Group): p1 = group.get_player_by_id(1) p2 = group.get_player_by_id(2) p1.payoff = C.ENDOWMENT - group.sent_amount + group.sent_back_amount p2.payoff = group.sent_amount * C.MULTIPLIER - group.sent_back_amount # PAGES class Introduction(Page): pass class Send(Page): """This page is only for P1 P1 sends amount (all, some, or none) to P2 This amount is tripled by experimenter, i.e if sent amount by P1 is 5, amount received by P2 is 15""" form_model = 'group' form_fields = ['sent_amount'] @staticmethod def is_displayed(player: Player): return player.id_in_group == 1 class SendBackWaitPage(WaitPage): pass class SendBack(Page): """This page is only for P2 P2 sends back some amount (of the tripled amount received) to P1""" form_model = 'group' form_fields = ['sent_back_amount'] @staticmethod def is_displayed(player: Player): return player.id_in_group == 2 @staticmethod def vars_for_template(player: Player): group = player.group tripled_amount = group.sent_amount * C.MULTIPLIER return dict(tripled_amount=tripled_amount) class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): """This page displays the earnings of each player""" @staticmethod def vars_for_template(player: Player): group = player.group return dict(tripled_amount=group.sent_amount * C.MULTIPLIER) page_sequence = [ Introduction, Send, SendBackWaitPage, SendBack, ResultsWaitPage, Results, ] trust / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} {{ if player.id_in_group == 1}} < p > You chose to send participant B {{group.sent_amount}}. Participant B returned {{group.sent_back_amount}}. < / p > < p > You were initially endowed with {{C.ENDOWMENT}}, chose to send {{group.sent_amount}}, received {{group.sent_back_amount}} thus you now have: {{C.ENDOWMENT}} - {{group.sent_amount}} + {{group.sent_back_amount}} = < strong > {{player.payoff}} < / strong > < / p > {{ else}} < p > Participant A sent you {{group.sent_amount}}. They were tripled so you received {{tripled_amount}}. You chose to return {{group.sent_back_amount}}. < / p > < p > You received {{tripled_amount}}, chose to return {{group.sent_back_amount}} thus you now have: ({{tripled_amount}}) - ({{group.sent_back_amount}}) = < strong > {{player.payoff}} < / strong > < / p > . {{endif}} < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} trust / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > You have been randomly and anonymously paired with another participant. One of you will be selected at random to be participant A; the other will be participant B. You will learn whether you are participant A or B prior to making any decision. < / p > < p > To start, participant A receives {{C.ENDOWMENT}}; participant B receives nothing. Participant A can send some or all of his {{C.ENDOWMENT}} to participant B. Before B receives this amount, it will be multiplied by {{C.MULTIPLIER}}.Once B receives the tripled amount he can decide to send some or all of it to A. < / p > < / div > < / div > trust / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} bertrand / __init__.py From otree - demo from otree.api import * doc = """ 2 firms complete in a market by setting prices for homogenous goods. See "Kruse, J. B., Rassenti, S., Reynolds, S. S., & Smith, V. L. (1994). Bertrand-Edgeworth competition in experimental markets. Econometrica: Journal of the Econometric Society, 343-371." """ class C(BaseConstants): PLAYERS_PER_GROUP = 2 NAME_IN_URL = 'bertrand' NUM_ROUNDS = 1 MAXIMUM_PRICE = cu(100) class Subsession(BaseSubsession): pass class Group(BaseGroup): winning_price = models.CurrencyField() class Player(BasePlayer): price = models.CurrencyField( min=0, max=C.MAXIMUM_PRICE, doc="""Price player offers to sell product for""", label="Please enter an amount from 0 to 100 as your price", ) is_winner = models.BooleanField() # FUNCTIONS def set_payoffs(group: Group): import random players = group.get_players() group.winning_price = min([p.price for p in players]) winners = [p for p in players if p.price == group.winning_price] winner = random.choice(winners) for p in players: if p == winner: p.is_winner = True p.payoff = p.price else: p.is_winner = False p.payoff = cu(0) # PAGES class Introduction(Page): pass class Decide(Page): form_model = 'player' form_fields = ['price'] class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): pass page_sequence = [Introduction, Decide, ResultsWaitPage, Results] bertrand / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < table class ="table" > < tr > < th > Your price < / th > < td > {{player.price}} < / td > < / tr > < tr > < th > Lowest price < / th > < td > {{group.winning_price}} < / td > < / tr > < tr > < th > Was your product sold? < / th > < td > {{ if player.is_winner}} Yes {{ else}} No {{endif}} < / td > < / tr > < tr > < th > Your payoff < / th > < td > {{player.payoff}} < / td > < / tr > < / table > {{next_button}} {{include_sibling 'instructions.html'}} {{endblock}} bertrand / Decide.html From otree - demo {{block title}}Set Your Price {{endblock}} {{block content}} {{formfields}} < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} bertrand / instructions.html From otree - demo < div class ="instructions well well-lg" style="" > < h3 > Instructions < / h3 > < p > You have been randomly and anonymously paired with another participant. Each of you will represent a firm.Each firm manufactures one unit of the same product at no cost. < / p > < p > Each of you privately sets your price, anything from 0 to {{C.MAXIMUM_PRICE}}. The buyer in the market will always buy one unit of the product at the lower price.In case of a tie, the buyer will buy from one of you at random.Your profit is your price if your product is sold and zero otherwise. < / p > < / div > bertrand / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} volunteer_dilemma / Decision.html From otree - demo {{block title}}Your Choice {{endblock}} {{block content}} {{formfields}} < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} volunteer_dilemma / __init__.py From otree - demo from otree.api import * doc = """ Each player decides if to free ride or to volunteer from which all will benefit. See: Diekmann, A. (1985). Volunteer's dilemma. Journal of Conflict Resolution, 605-610. """ class C(BaseConstants): NAME_IN_URL = 'volunteer_dilemma' PLAYERS_PER_GROUP = 3 NUM_ROUNDS = 1 NUM_OTHER_PLAYERS = PLAYERS_PER_GROUP - 1 # """Payoff for each player if at least one volunteers""" GENERAL_BENEFIT = cu(100) # """Cost incurred by volunteering player""" VOLUNTEER_COST = cu(40) class Subsession(BaseSubsession): pass class Group(BaseGroup): num_volunteers = models.IntegerField() class Player(BasePlayer): volunteer = models.BooleanField( label='Do you wish to volunteer?', doc="""Whether player volunteers""" ) # FUNCTIONS def set_payoffs(group: Group): players = group.get_players() group.num_volunteers = sum([p.volunteer for p in players]) if group.num_volunteers > 0: baseline_amount = C.GENERAL_BENEFIT else: baseline_amount = cu(0) for p in players: p.payoff = baseline_amount if p.volunteer: p.payoff -= C.VOLUNTEER_COST # PAGES class Introduction(Page): pass class Decision(Page): form_model = 'player' form_fields = ['volunteer'] class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): pass page_sequence = [Introduction, Decision, ResultsWaitPage, Results] volunteer_dilemma / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < p > {{ if player.volunteer}} You volunteered.As a result, your payoff is < strong > {{player.payoff}} < / strong >. {{ elif group.num_volunteers > 0}} You did not volunteer but some did.As a result, your payoff is < strong > {{player.payoff}} < / strong >. {{ else}} You did not volunteer and no one did.As a result, your payoff is < strong > {{player.payoff}} < / strong >. {{endif}} < / p > < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} volunteer_dilemma / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > You will be grouped randomly and anonymously with another {{C.NUM_OTHER_PLAYERS}} participants. < / p > < p > Each of you decides independently and simultaneously whether you will volunteer or not.If at least one of you volunteers, everyone will get {{C.GENERAL_BENEFIT}}.However, the volunteer(s) will pay {{C.VOLUNTEER_COST}}.If no one volunteers, everyone receives nothing. < / p > < / div > < / div > volunteer_dilemma / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} guess_two_thirds / Guess.html From otree - demo {{block title}}Your Guess {{endblock}} {{block content}} {{ if player.round_number > 1}} < p > Here were the two - thirds - average values in previous rounds: {{two_thirds_avg_history}} < / p > {{endif}} {{formfields}} {{next_button}} {{include_sibling 'instructions.html'}} {{endblock}} guess_two_thirds / __init__.py From otree - demo from otree.api import * doc = """ a.k.a. Keynesian beauty contest. Players all guess a number; whoever guesses closest to 2/3 of the average wins. See https://en.wikipedia.org/wiki/Guess_2/3_of_the_average """ class C(BaseConstants): PLAYERS_PER_GROUP = 3 NUM_ROUNDS = 3 NAME_IN_URL = 'guess_two_thirds' JACKPOT = cu(100) GUESS_MAX = 100 class Subsession(BaseSubsession): pass class Group(BaseGroup): two_thirds_avg = models.FloatField() best_guess = models.IntegerField() num_winners = models.IntegerField() class Player(BasePlayer): guess = models.IntegerField( min=0, max=C.GUESS_MAX, label="Please pick a number from 0 to 100:" ) is_winner = models.BooleanField(initial=False) # FUNCTIONS def set_payoffs(group: Group): players = group.get_players() guesses = [p.guess for p in players] two_thirds_avg = (2 / 3) * sum(guesses) / len(players) group.two_thirds_avg = round(two_thirds_avg, 2) group.best_guess = min(guesses, key=lambda guess: abs(guess - group.two_thirds_avg)) winners = [p for p in players if p.guess == group.best_guess] group.num_winners = len(winners) for p in winners: p.is_winner = True p.payoff = C.JACKPOT / group.num_winners def two_thirds_avg_history(group: Group): return [g.two_thirds_avg for g in group.in_previous_rounds()] # PAGES class Introduction(Page): @staticmethod def is_displayed(player: Player): return player.round_number == 1 class Guess(Page): form_model = 'player' form_fields = ['guess'] @staticmethod def vars_for_template(player: Player): group = player.group return dict(two_thirds_avg_history=two_thirds_avg_history(group)) class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): @staticmethod def vars_for_template(player: Player): group = player.group sorted_guesses = sorted(p.guess for p in group.get_players()) return dict(sorted_guesses=sorted_guesses) page_sequence = [Introduction, Guess, ResultsWaitPage, Results] guess_two_thirds / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < p > Here were the numbers guessed: < / p > < p > {{sorted_guesses}} < / p > < p > Two - thirds of the average of these numbers is {{group.two_thirds_avg}}; the closest guess was {{group.best_guess}}. < / p > < p > Your guess was {{player.guess}}. < / p > < p > {{ if player.is_winner}} {{ if group.num_winners > 1}} Therefore, you are one of the {{group.num_winners}} winners who tied for the best guess. {{ else}} Therefore, you win! {{endif}} {{ else}} Therefore, you did not win. {{endif}} Your payoff is {{player.payoff}}. < / p > {{next_button}} {{include_sibling 'instructions.html'}} {{endblock}} guess_two_thirds / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > You are in a group of {{C.PLAYERS_PER_GROUP}} people. Each of you will be asked to choose a number between 0 and {{C.GUESS_MAX}}. The winner will be the participant whose number is closest to 2 / 3 of the average of all chosen numbers. < / p > < p > The winner will receive {{C.JACKPOT}}. In case of a tie, the {{C.JACKPOT}} will be equally divided among winners. < / p > < p > This game will be played for {{C.NUM_ROUNDS}} rounds. p > < / div > < / div > guess_two_thirds / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} bargaining / Request.html From otree - demo {{block title}}Request {{endblock}} {{block content}} < p > How much will you demand for yourself? < / p > {{formfields}} < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} bargaining / __init__.py From otree - demo from otree.api import * doc = """ This bargaining game involves 2 players. Each demands for a portion of some available amount. If the sum of demands is no larger than the available amount, both players get demanded portions. Otherwise, both get nothing. """ class C(BaseConstants): NAME_IN_URL = 'bargaining' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 AMOUNT_SHARED = cu(100) class Subsession(BaseSubsession): pass class Group(BaseGroup): total_requests = models.CurrencyField() class Player(BasePlayer): request = models.CurrencyField( doc=""" Amount requested by this player. """, min=0, max=C.AMOUNT_SHARED, label="Please enter an amount from 0 to 100", ) # FUNCTIONS def set_payoffs(group: Group): players = group.get_players() group.total_requests = sum([p.request for p in players]) if group.total_requests <= C.AMOUNT_SHARED: for p in players: p.payoff = p.request else: for p in players: p.payoff = cu(0) def other_player(player: Player): return player.get_others_in_group()[0] # PAGES class Introduction(Page): pass class Request(Page): form_model = 'player' form_fields = ['request'] class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): @staticmethod def vars_for_template(player: Player): return dict(other_player_request=other_player(player).request) page_sequence = [Introduction, Request, ResultsWaitPage, Results] bargaining / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < table class =table style="width: auto" > < tr > < th > You demanded < / th > < td > {{player.request}} < / td > < / tr > < tr > < th > The other participant demanded < / th > < td > {{other_player_request}} < / td > < / tr > < tr > < th > Sum of your demands < / th > < td > {{group.total_requests}} < / td > < / tr > < tr > < th > Thus you earn < / th > < td > {{player.payoff}} < / td > < / tr > < / table > < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} bargaining / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > You have been randomly and anonymously paired with another participant. There is {{C.AMOUNT_SHARED}} for you to divide. Both of you have to simultaneously and independently demand a portion of the {{C.AMOUNT_SHARED}} for yourselves.If the sum of your demands is smaller or equal to {{C.AMOUNT_SHARED}}, both of you get what you demanded.If the sum of your demands is larger than {{C.AMOUNT_SHARED}}, both of you get nothing. < / p > < / div > < / div > bargaining / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} prisoner / Decision.html From otree - demo {{block title}}Your Choice {{endblock}} {{block content}} < div class ="form-group required" > < table class ="table table-bordered text-center" style="width: auto; margin: auto" > < tr > < th colspan = "2" rowspan = "2" > < / th > < th colspan = "2" > The Other Participant < / th > < / tr > < tr > < th > Cooperate < / th > < th > Defect < / th > < / tr > < tr > < th rowspan = "2" > < span > You < / span > < / th > < td > < button name = "cooperate" value = "True" class ="btn btn-primary btn-large" > I will cooperate < / button > < / td > < td > {{C.PAYOFF_B}}, {{C.PAYOFF_B}} < / td > < td > {{C.PAYOFF_D}}, {{C.PAYOFF_A}} < / td > < / tr > < tr > < td > < button name = "cooperate" value = "False" class ="btn btn-primary btn-large" > I will defect < / button > < / td > < td > {{C.PAYOFF_A}}, {{C.PAYOFF_D}} < / td > < td > {{C.PAYOFF_C}}, {{C.PAYOFF_C}} < / td > < / tr > < / table > < / div > < p > Here you can chat with the other participant.< / p > {{chat}} {{include_sibling 'instructions.html'}} {{endblock}} prisoner / __init__.py From otree - demo from otree.api import * doc = """ This is a one-shot "Prisoner's Dilemma". Two players are asked separately whether they want to cooperate or defect. Their choices directly determine the payoffs. """ class C(BaseConstants): NAME_IN_URL = 'prisoner' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 PAYOFF_A = cu(300) PAYOFF_B = cu(200) PAYOFF_C = cu(100) PAYOFF_D = cu(0) class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): cooperate = models.BooleanField( choices=[[True, 'Cooperate'], [False, 'Defect']], doc="""This player's decision""", widget=widgets.RadioSelect, ) # FUNCTIONS def set_payoffs(group: Group): for p in group.get_players(): set_payoff(p) def other_player(player: Player): return player.get_others_in_group()[0] def set_payoff(player: Player): payoff_matrix = { (False, True): C.PAYOFF_A, (True, True): C.PAYOFF_B, (False, False): C.PAYOFF_C, (True, False): C.PAYOFF_D, } other = other_player(player) player.payoff = payoff_matrix[(player.cooperate, other.cooperate)] # PAGES class Introduction(Page): timeout_seconds = 100 class Decision(Page): form_model = 'player' form_fields = ['cooperate'] class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): @staticmethod def vars_for_template(player: Player): opponent = other_player(player) return dict( opponent=opponent, same_choice=player.cooperate == opponent.cooperate, my_decision=player.field_display('cooperate'), opponent_decision=opponent.field_display('cooperate'), ) page_sequence = [Introduction, Decision, ResultsWaitPage, Results] prisoner / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < p > {{ if same_choice}} Both of you chose to {{my_decision}}. {{ else}} You chose to {{my_decision}} and the other participant chose to {{opponent_decision}}. {{endif}} < / p > < p > As a result, you earned {{player.payoff}}. < / p > {{next_button}} {{include_sibling 'instructions.html'}} {{endblock}} prisoner / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > In this study, you will be randomly and anonymously paired with another participant. Each of you simultaneously and privately chooses whether you want to cooperate or defect. Your payoffs will be determined by the choices of both as below: < / p > < p > < i > In each cell, the amount to the left is the payoff for you and to the right for the other participant.< / i > < / p > < table class ='table table-bordered text-center' style = 'width: auto; margin: auto' > < tr > < th colspan = 2 rowspan = 2 > < / th > < th colspan = 2 > The Other Participant < / th > < / tr > < tr > < th > Cooperate < / th > < th > Defect < / th > < / tr > < tr > < th rowspan = 2 > < span style = "transform: rotate(-90deg);" > You < / span > < / th > < th > Cooperate < / th > < td > {{C.PAYOFF_B}}, {{C.PAYOFF_B}} < / td > < td > 0, {{C.PAYOFF_A}} < / td > < / tr > < tr > < th > Defect < / th > < td > {{C.PAYOFF_A}}, 0 < / td > < td > {{C.PAYOFF_C}}, {{C.PAYOFF_C}} < / td > < / tr > < / table > < / div > < / div > prisoner / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} public_goods_simple / __init__.py From otree - demo from otree.api import * class C(BaseConstants): NAME_IN_URL = 'public_goods_simple' PLAYERS_PER_GROUP = 3 NUM_ROUNDS = 1 ENDOWMENT = cu(100) MULTIPLIER = 1.8 class Subsession(BaseSubsession): pass class Group(BaseGroup): total_contribution = models.CurrencyField() individual_share = models.CurrencyField() class Player(BasePlayer): contribution = models.CurrencyField( min=0, max=C.ENDOWMENT, label="How much will you contribute?" ) # FUNCTIONS def set_payoffs(group: Group): players = group.get_players() contributions = [p.contribution for p in players] group.total_contribution = sum(contributions) group.individual_share = ( group.total_contribution * C.MULTIPLIER / C.PLAYERS_PER_GROUP ) for p in players: p.payoff = C.ENDOWMENT - p.contribution + group.individual_share # PAGES class Contribute(Page): form_model = 'player' form_fields = ['contribution'] class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): pass page_sequence = [Contribute, ResultsWaitPage, Results] public_goods_simple / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < p > You started with an endowment of {{C.ENDOWMENT}}, of which you contributed {{player.contribution}}. Your group contributed {{group.total_contribution}}, resulting in an individual share of {{group.individual_share}}. Your profit is therefore {{player.payoff}}. < / p > {{next_button}} {{endblock}} public_goods_simple / Contribute.html From otree - demo {{extends "global/Page.html"}} {{block title}}Contribute {{endblock}} {{block content}} < p > This is a public goods game with {{C.PLAYERS_PER_GROUP}} players per group, an endowment of {{C.ENDOWMENT}}, and an efficiency factor of {{C.MULTIPLIER}}. < / p > {{formfields}} {{next_button}} {{endblock}} traveler_dilemma / __init__.py From otree - demo from otree.api import * doc = """ Kaushik Basu's famous traveler's dilemma ( AER 1994 ). It is a 2-player game. The game is framed as a traveler's dilemma and intended for classroom/teaching use. """ class C(BaseConstants): NAME_IN_URL = 'traveler_dilemma' PLAYERS_PER_GROUP = 2 NUM_ROUNDS = 1 # Player's reward for the lowest claim""" ADJUSTMENT_ABS = cu(2) # Player's deduction for the higher claim # The maximum claim to be requested MAX_AMOUNT = cu(100) # The minimum claim to be requested MIN_AMOUNT = cu(2) class Subsession(BaseSubsession): pass class Group(BaseGroup): lower_claim = models.CurrencyField() class Player(BasePlayer): claim = models.CurrencyField( min=C.MIN_AMOUNT, max=C.MAX_AMOUNT, label='How much will you claim for your antique?', doc=""" Each player's claim """, ) adjustment = models.CurrencyField() # FUNCTIONS def set_payoffs(group: Group): p1, p2 = group.get_players() if p1.claim == p2.claim: group.lower_claim = p1.claim for p in [p1, p2]: p.payoff = group.lower_claim p.adjustment = cu(0) else: if p1.claim < p2.claim: winner = p1 loser = p2 else: winner = p2 loser = p1 group.lower_claim = winner.claim winner.adjustment = C.ADJUSTMENT_ABS loser.adjustment = -C.ADJUSTMENT_ABS winner.payoff = group.lower_claim + winner.adjustment loser.payoff = group.lower_claim + loser.adjustment def other_player(player: Player): return player.get_others_in_group()[0] # PAGES class Introduction(Page): pass class Claim(Page): form_model = 'player' form_fields = ['claim'] class ResultsWaitPage(WaitPage): after_all_players_arrive = set_payoffs class Results(Page): @staticmethod def vars_for_template(player: Player): return dict(other_player_claim=other_player(player).claim) page_sequence = [Introduction, Claim, ResultsWaitPage, Results] traveler_dilemma / Results.html From otree - demo {{block title}}Results {{endblock}} {{block content}} < table class =table style='width: auto' > < tr > < td > You claimed < / td > < td > {{player.claim}} < / td > < / tr > < tr > < td > The other traveler claimed < / td > < td > {{other_player_claim}} < / td > < / tr > < tr > < td > Winning claim(i.e.lower claim) < / td > < td > {{group.lower_claim}} < / td > < / tr > < tr > < td > Your adjustment < / td > < td > {{player.adjustment}} < / td > < / tr > < tr > < td > Thus you receive < / td > < td > {{player.payoff}} < / td > < / tr > < / table > < p > {{next_button}} < / p > {{include_sibling 'instructions.html'}} {{endblock}} traveler_dilemma / instructions.html From otree - demo < div class ="card bg-light m-3" > < div class ="card-body" > < h3 > Instructions < / h3 > < p > You have been randomly and anonymously paired with another participant. Now please image the following scenario. < / p > < p > You and another traveler(the other participant) just returned from a remote island where both of you bought the same antiques. Unfortunately, you discovered that your airline managed to smash the antiques, as they always do.The airline manager assures you of adequate compensation.Without knowing the true value of your antiques, he offers you the following scheme.Both of you simultaneously and independently make a claim for the value of your own antique (ranging from {{C.MIN_AMOUNT}} to {{C.MAX_AMOUNT}}): < / p > < ul > < li > If both claim the same amount, then this amount will be paid to both. < / li > < li > If you claim different amounts, then the lower amount will be paid to both.Additionally, the one with lower claim will receive a reward of {{C.ADJUSTMENT_ABS}}; the one with higher claim will receive a penalty of {{C.ADJUSTMENT_ABS}}. < / li > < / ul > < / div > < / div > traveler_dilemma / Claim.html From otree - demo {{block title}}Claim {{endblock}} {{block content}} {{formfields}} {{next_button}} {{include_sibling 'instructions.html'}} {{endblock}} traveler_dilemma / Introduction.html From otree - demo {{block title}}Introduction {{endblock}} {{block content}} {{include_sibling 'instructions.html'}} {{next_button}} {{endblock}} matching_pennies / ResultsSummary.html From otree - demo {{block title}}Final results {{endblock}} {{block content}} < table class ="table" > < tr > < th > Round < / th > < th > Player and outcome < / th > < / tr > {{ for p in player_in_all_rounds}} < tr > < td > {{p.round_number}} < / td > < td > You were the {{p.role}} and {{ if p.is_winner}} won {{ else}} lost {{endif}} < / td > < / tr > {{endfor}} < / table > < p > The paying round was {{paying_round}}. Your total payoff is therefore {{total_payoff}}. < / p > {{endblock}} survey / __init__.py From otree - demo from otree.api import * class C(BaseConstants): NAME_IN_URL = 'survey' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): age = models.IntegerField(label='What is your age?', min=13, max=125) gender = models.StringField( choices=[['Male', 'Male'], ['Female', 'Female']], label='What is your gender?', widget=widgets.RadioSelect, ) crt_bat = models.IntegerField( label=''' A bat and a ball cost 22 dollars in total. The bat costs 20 dollars more than the ball. How many dollars does the ball cost?''' ) crt_widget = models.IntegerField( label=''' If it takes 5 machines 5 minutes to make 5 widgets, how many minutes would it take 100 machines to make 100 widgets? ''' ) crt_lake = models.IntegerField( label=''' In a lake, there is a patch of lily pads. Every day, the patch doubles in size. If it takes 48 days for the patch to cover the entire lake, how many days would it take for the patch to cover half of the lake? ''' ) # FUNCTIONS # PAGES class Demographics(Page): form_model = 'player' form_fields = ['age', 'gender'] class CognitiveReflectionTest(Page): form_model = 'player' form_fields = ['crt_bat', 'crt_widget', 'crt_lake'] page_sequence = [Demographics, CognitiveReflectionTest] survey / Demographics.html From otree - demo {{block title}}Survey {{endblock}} {{block content}} < p > Please answer the following questions. < / p > {{formfields}} {{next_button}} {{endblock}} payment_info / __init__.py From otree - demo from otree.api import * doc = """ This application provides a webpage instructing participants how to get paid. Examples are given for the lab and Amazon Mechanical Turk (AMT). """ class C(BaseConstants): NAME_IN_URL = 'payment_info' PLAYERS_PER_GROUP = None NUM_ROUNDS = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): pass # FUNCTIONS # PAGES class PaymentInfo(Page): @staticmethod def vars_for_template(player: Player): participant = player.participant return dict(redemption_code=participant.label or participant.code) page_sequence = [PaymentInfo] payment_info / PaymentInfo.html From otree - demo {{block title}}Thank you {{endblock}} {{block content}} < p > < em > Below are examples of messages that could be displayed for different experimental settings.< / em > < / p > < div class ="panel panel-default" style="margin-bottom:10px" > < div class ="panel-body" > < p > < b > Laboratory: < / b > < / p > < p > Please remain seated until your number is called.Then take your number card, and proceed to the cashier. < / p > < p > < em > Note: For the cashier in the laboratory, oTree can print a list of payments for all participants as a PDF.< / em > < / p > < / div > < / div > < div class ="panel panel-default" style="margin-bottom:10px" > < div class ="panel-body" > < p > < b > Classroom: < / b > < / p > < p > < em > If you want to keep track of how students did, the easiest thing is to assign the starting links to students by name. It is even possible to give each student a single permanent link for a whole semester using Rooms; so no need to waste time in each lecture with handing out new links and keeping track of which student uses which link. Alternatively, you may just give students anonymous links or secret nicknames. < / em > < / p > < / div > < / div > {{endblock}} common_value_auction / __init__.py From otree - demo from otree.api import * doc = """ In a common value auction game, players simultaneously bid on the item being auctioned.